2
brand(id, parent_id, name)
      1 |     0    | Apple
      2 |     0    | Samsung
      3 |     1    | Iphone 3S
      4 |     1    | Iphone 4S
product(id, name)
        1 | OS
        2 | Andriod
product_brand(product_id, brand_id)
                  1     |    3
                  1     |    4

和 mysql:如何获取product name何时brand name = Apple

SELECT * FROM product_brand
LEFT JOIN brand ON brand.id = product_brand.brand_id
WHERE brand.id = 1 // Apple

例如:如果得到 Apple(id=1) 是结果 => 操作系统,如果得到三星(id=2) 是结果 => Andriod

4

3 回答 3

1

如果您想获取未存储在 product_brand 中的 Apple 和 Samsung 的产品名称(请参见示例数据)。您可以按如下方式修复查询:

 SELECT *,
    CASE b.name WHEN 'Apple' THEN 'iOS'
    WHEN 'Samsung' THEN 'Android' ELSE '-' END  
   FROM
    brand b

编辑2:如果要根据parent_id获取所有产品名称。可以试试下面的:

SELECT *,
    CASE b.name WHEN 'Apple' THEN 'iOS'
    WHEN 'Samsung' THEN 'Android' ELSE '-' END as type_of_os
FROM
    brand b 
WHERE parent_id=0
UNION
SELECT
    b.*,
    CASE b2.name WHEN 'Apple' THEN 'iOS'
    WHEN 'Samsung' THEN 'Android' ELSE '-' END as type_of_os
FROM
    brand b
INNER JOIN
    brand b2 ON b.parent_id = b2.id 

http://sqlfiddle.com/#!2/1f573/18

于 2012-06-27T02:18:19.137 回答
1

尝试这个:

SELECT
  p.name
FORM product p
LEFT JOIN product_brand pb ON p.id = pb.product_id
LEFT JOIN brand b ON pb.brand_id = b.id
LEFT JOIN brand b1 ON b.id = b1.parent_id
WHERE b1.name = 'Apple' 
于 2012-06-27T02:10:07.403 回答
1

你的意思是像

SELECT
  childbrand,name AS child_brand_name
  product.name AS product_name
FROM brand AS childbrand
INNER JOIN brand AS parentbrand ON parentbrand.id=childbrand.parent_id
INNER JOIN product_brand ON product_brand.brand_id=childbrand.id
INNER JOIN product ON product_brand.product_id=product.id
WHERE parentbrand.name='Apple';
于 2012-06-27T02:13:59.493 回答