使用连接表选择与所有指定行匹配的行

时间:2014-03-13 20:12:19

标签: mysql join

我正在尝试编写一个查询,它将返回所有具有类别a和类别b的程序。表结构如下:

程序

id
1000
1001
1002

Program_Category

program_id | category_id
1000       | 1
1000       | 2

分类

id          | name
1           | category a
2           | category b

如您所见,程序1000具有类别a和类别b。我试图用来检索程序的查询是

SELECT DISTINCT t1.id 
FROM PROGRAM t1 
LEFT OUTER JOIN (PROGRAM_CATEGORY t2 
                 JOIN CATEGORY t0 ON (t0.id = t2.category_id)
) ON (t2.program_id = t1.id) 
WHERE ((t0.name = 'category a') 
   AND (t0.name = 'category b'))

目前返回0行。

4 个答案:

答案 0 :(得分:1)

我无法猜测您的查询尝试了什么,但我认为这对您有用

SELECT count(*), p.ID FROM Program p
INNER JOIN Program_Category pc ON pc.program_id = p.id
INNER JOIN Category c ON pc.category_id = c.category_id 
WHERE c.category_name = 'category a' or c.category_name = 'category b'
GROUP BY p.ID HAVING count(*) >= 2

这将使任何出现两次匹配任何这些类别的程序。

如果(program_id,category_id)不是唯一的键,这将不起作用。 我的意思是,如果Program_Category可以有两倍于1000,1

,那么这将失败

答案 1 :(得分:1)

常规JOIN可以相当直接的方式完成;

SELECT pc1.program_id 
FROM program_category pc1
JOIN program_category pc2
  ON pc1.program_id = pc2.program_id
JOIN category c1
  ON c1.category_id = pc1.category_id AND c1.name = 'category a'
JOIN category c2
  ON c2.category_id = pc2.category_id AND c2.name = 'category b'

An SQLfiddle to test with

答案 2 :(得分:0)

尝试加入category的两个实例。此查询会检查p是否与“类别a”和“类别b”相关,即使(program_id, category_id)不唯一,该查询也会有效:

SELECT distinct p.id
FROM PROGRAM p JOIN program_category pc1 ON p.id = pc1.program_id
       JOIN category c1 ON pc1.category_id = c1.id
       JOIN program_category pc2 ON p.id = pc2.program_id
       JOIN category c2 ON pc2.category_id = c2.id
WHERE c1.category_name = 'category a'
AND c2.category_name = 'category b';

答案 3 :(得分:0)

您正在根据您的表定义访问t0.id,实际上是t0.category_id。