MYSQL - 获取所有选定类别中的行

时间:2011-06-01 13:27:54

标签: mysql relational-database

我正在尝试向MYSQL数据库写入查询,该数据库查询与所有选定类别有关系的产品

产品表

product_id | product_name
---------------------------------
    1      | product name one
    2      | product name two
    3      | product three

类别表

category_id | category_name
    1       | category one
    2       | category two
    3       | category three

Category_relationship表

product_id | category_id
--------------------------
    1      |    1
    1      |    2
    1      |    3
    2      |    1
    2      |    2
    3      |    3

例如:

  • 选择类别ID 1和3
  • 只返回product_id为'1'

5 个答案:

答案 0 :(得分:1)

加入两次:

select p.*
from products p
join category_relationship c1 on c1.product_id = p.product_id
                             and c1.category_id = 1
join category_relationship c2 on c2.product_id = p.product_id
                             and c2.category_id = 3

答案 1 :(得分:1)

使用2个JOIN

SELECT
    p.*
FROM products p
  JOIN category_relationship r1 
    ON r1.product_id = p.product_id 
  JOIN category_relationship r2
    ON r2.product_id = p.product_id 
WHERE r1.category_id = 1
  AND r2.category_id = 3

使用GROUP BY

SELECT
    p.*
FROM products p
  JOIN category_relationship r 
    ON r.product_id = p.product_id 
WHERE r.category_id IN (1,3)
GROUP BY p.product_id 
HAVING COUNT(*) = 2             <-- number of category ids

这取决于您的表格大小和数据分布,但我猜第一个查询要更快。

但是如果要检查各种大小的列表(使用3,4,...类别ID),则必须动态构建第一个查询,而第二个查询可以轻松调整。

答案 2 :(得分:0)

试试这个:

SELECT DISTINCT product_id FROM category_relationship WHERE category_id IN (1, 3)

答案 3 :(得分:0)

例如:

SELECT * 
  FROM Products P, Category_relationship CP
 WHERE P.product_id = CP.product_id
   AND CP.category_id IN (1,3)

答案 4 :(得分:0)

SELECT p.product_id, p.product_name
FROM products p LEFT JOIN category_relationship cp ON p.product_id = cp.product_id
GROUP BY p.product_id, p.product_name
HAVING COUNT(cp.category_id) = (SELECT COUNT(*) FROM categories)