mysql select multitable - join

时间:2013-03-13 07:27:47

标签: php mysql sql relational-division

说我有以下表格

user_table 
id    username
1     abc
2     def
3     ghij

courses_table 
id    title
1     csc
2     math
3     syn

user_courses 
user_id    course_id
2           1
1           3
2           3

我想选择参加课程1和3的用户名, 不是至少1或3,我的意思是1和3

我尝试了以下mysql查询

SELECT DISTINCT  u.* FROM  user_table as u  LEFT JOIN user_courses as uc ON uc.user_id = u.id  WHERE uc.course_id = 1 AND uc.course_id=3;
SELECT DISTINCT  u.* FROM  user_table as u  LEFT JOIN user_courses as uc ON uc.user_id = u.id  WHERE uc.course_id IN (1,3);
SELECT DISTINCT  u.* FROM  user_table as u  LEFT JOIN user_courses as uc ON uc.user_id = u.id  WHERE uc.course_id IN (1,3) AND uc.user_id = u.id ;

执行的第一个和第三个查询未显示任何结果,第二个查询显示至少拥有course_id 1或3的所有用户

如果你想知道为什么我使用LEFT JOIN,这是因为我需要连接表的结果,上面的代码行只是一个例子,我用来从大约9个表中使用LEFT连接获取数据

有什么帮助吗?谢谢

SELECT DISTINCT  u.* FROM  user_table as u  LEFT JOIN user_courses as uc ON uc.user_id = u.id  WHERE uc.course_id IN( 1,3) AND uc.user_id = 2 ";

这告诉我我想要的结果,它的输出“def”, 但我不能将user_id用作静态值(本例中为数字2)

2 个答案:

答案 0 :(得分:5)

此问题称为Relational Division

SELECT  a.id, a.username
FROM    user_table a
        INNER JOIN user_courses b
            ON a.id = b.user_ID
WHERE   b.course_ID IN (1,3)
GROUP   BY a.id, a.username
HAVING  COUNT(*) = 2

如果考虑到用户重新参加课程,course_ID并非每个用户都是唯一的,则需要DISTINCT个关键字才能开设独特的课程,

SELECT  a.id, a.username
FROM    user_table a
        INNER JOIN user_courses b
            ON a.id = b.user_ID
WHERE   b.course_ID IN (1,3)
GROUP   BY a.id, a.username
HAVING  COUNT(DISTINCT b.course_ID) = 2

输出

╔════╦══════════╗
║ ID ║ USERNAME ║
╠════╬══════════╣
║  2 ║ def      ║
╚════╩══════════╝

答案 1 :(得分:0)

请试试这个:

SELECT 
  U.id,
  U.username
FROM
  user_courses UC 
  INNER JOIN user_table U 
    ON UC.`user_id` = U.`id` 
WHERE UC.`course_id` = 1 
  OR UC.`course_id` = 3 
  GROUP BY U.`id` 
  HAVING COUNT(*) > 1