2013-02-11 58 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