2013-02-11 30 views
-1

比方说,我在我的MySQL数据库下表:MySQL的加入和列名

TABLE Products 
| id | some_column1 | some_column2 | 

TABLE ProductProperties 
| id | product_id | name | 

过于简单,但足够了。现在我想要获得所有具有属性的产品。我这样做:

SELECT * FROM `Products` JOIN `ProductProperties` ON Products.id = ProductProperties.product_id 

我得到了什么?

| id | some_column1 | some_column2 | id | product_id | name | 

这是不冷静的,我希望把它清凉的两种方法之一:

1)要获得对象的数组喜欢在产品表,但多了一个成员,延长其将是与JOIN匹配的属性数组。我已经知道这是不可能的?

2)为了得到这样的阵列(我仍然要遍历在PHP中加入所有属性于一身的产品合并到一个对象):

| product_id | some_column1 | some_column2 | property_id | product_id | name | 

所以我想重新命名将ProductProperties.id列转换为ProductProperties.property_id。如果我也可以从输出中移除ProductProperties.product_id,那将是理想的,但现在,我只想要重新命名输出中的一列。或者以表名为前缀。或类似的东西。

可以吗?

+1

您能否提供测试数据和预期结果? – 2013-02-11 19:48:46

回答

3

您应明确指定列的名称,而不要使用*。然后,不返回冗余列:

SELECT p.id as productid, p.some_column1, p.some_column2, 
     pp.id as ProductPropertiesId, pp.name 
FROM `Products` p JOIN `ProductProperties` pp 
    ON p.id = pp.product_id 

此外,表别名做出这样的查询更具可读性。

+0

哈,那很容易。我承认,我不知道SQL,只有当我必须使用它时。谢谢你的回答。 – 2013-02-11 20:30:55

+3

@AlW。 。 。你的问题似乎是来自没有太多经验的人。不幸的是,我认为,人们倾向于自动降低这些问题,而不是意识到存在学习曲线。 – 2013-02-11 20:32:55

1
SELECT Products.id product_id, 
     Products.some_column1, 
     Products.some_column2, 
     ProductProperties.id property_id, 
     ProductProperties.name 
FROM `Products` 
JOIN `ProductProperties` 
ON Products.id = ProductProperties.product_id