簡體   English   中英

MySQL連接和列名

[英]MySQL join and column names

假設我的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)獲得類似於Product表中的對象數組,但又擴展了一個成員,這將是與JOIN匹配的屬性數組。 我已經弄清楚這是不可能的嗎?

2)要獲得這樣的數組(我仍然必須在PHP中對其進行迭代,以將一種產品中的所有屬性連接到一個對象中):

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

因此,我想將ProductProperties.id列重命名為ProductProperties.property_id。 如果我也可以從輸出中刪除ProductProperties.product_id,那將是理想的選擇,但是就目前而言,我只想在輸出中重命名一列。 或在表名前添加前綴。 或類似的東西。

可行嗎

您應該顯式命名列,而不要使用* 然后,不要返回多余的列:

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

此外,表別名使此類查詢更具可讀性。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM