0

我有一张桌子:

brand(id, parent_id, name)
       1      0      Apple 
       2      1      Macbook Air
       3      1      Iphone 4S
imgae(id, brand_id, image)
       1      2      mac.png
       2      3      iphone.png

和mysql:

SELECT br.name, img.image FROM image as img
LEFT JOIN brand AS br ON br.parent_id = img.brand_id

结果是:

Macbook Air |   mac.png
Iphone 4S   |   iphone.png

如何从表品牌中获取父名称

Macbook Air |   mac.png     | Apple
Iphone 4S   |   iphone.png  | Apple 
4

2 回答 2

3
SELECT brand.id, brand.name, brandName.name as parentName, images.image FROM brand 
INNER JOIN brand as brandName ON brand.parent_id=brandName.id 
LEFT JOIN images ON brand.id=images.brand_id

我将 LEFT JOIN 更改为 INNER JOIN

请再检查一次。

于 2012-06-24T10:13:05.670 回答
2

当你遇到这样的问题时,我尽量不要使用自引用表。再看看你的数据库/表设计。

Manufacture(
 ID
,Name)

Image(
 ID
,Blob
,URL)

Product(
 ID
,ImageID
,ManID
,Name
,Description
)

SQL

Select 
     M.Name as Brand
    ,P.Name as Product
    ,I.URL as ImageURL
FROM 
    Product AS P
JOIN Manufacture AS M ON
    P.ManID = M.ID
LEFT JOIN Image AS I ON
    P.ImageID = I.ID`

希望有帮助。

PS。我还建议从管理的角度拆分您的表格。假设您希望删除所有 Apple 产品,您可以从 Manufacture 表中删除 Apple(通过将列设置IsActive0,并更新 SQL 以仅选择行WHERE M.IsActive = 1)删除 Apple 和通过 ManID 链接的所有产品。

于 2012-06-24T10:24:48.443 回答