mysql如何加入获取数据

时间:2012-12-29 17:45:40

标签: php mysql sql join

  

可能重复:
  How can an SQL query return data from multiple tables

我有3张桌子

属性

attr_id | attr_name 
1       | oval<
2       | white

产品

product_id|product_name 
1         | amazonite 
2         | agate

attr_detail

attr_detail_id | attr_id | product_id
1              | 1       | 1
2              | 2       | 1
3              | 1       | 2
4              | 2       | 2

现在我想要的产品是椭圆形和白色。如何使用join。

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT DISTINCT
  p.product_id, 
  p.product_name 
FROM Product p 
INNER JOIN attr_detail ad ON p.product_id = ad.product_Id
INNER JOIN Attribute a    ON a.attr_id = ad.attr_id
WHERE a.attr_id IN(1, 2);

SQL Fiddle Demo

这会给你:

| PRODUCT_ID |           PRODUCT_NAME |
---------------------------------------
|          1 |              amazonite |
|          2 |                  agate |
|          3 | Product has only white |

请注意:这将为您提供具有whiteoval形状的产品名称。 然而,如果您只查找同时具有这两种形状的产品,则必须修改您的查询,如下所示:

SELECT DISTINCT
  p.product_id, 
  p.product_name 
FROM Product p 
INNER JOIN
(
  SELECT product_id
  FROM attr_detail
  WHERE attr_id IN(1, 2)
  GROUP BY product_id
  HAVING COUNT(DISTINCT attr_id) = 2
) ad ON p.product_id = ad.product_Id;

Updated SQL Fiddle Demo

这会给你:

| PRODUCT_ID | PRODUCT_NAME |
-----------------------------
|          1 |    amazonite |
|          2 |        agate |

请详细了解JOIN s。在这里您可以找到有关此内容的有用信息:

我在第二个查询中做了什么:

  SELECT product_id
  FROM attr_detail
  WHERE attr_id IN(1, 2)
  GROUP BY product_id
  HAVING COUNT(DISTINCT attr_id) = 2

这称为Relational Division