简体   繁体   English

MySQL选择多表-加入

[英]mysql select multitable - join

say i had the following tables 说我有下表

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

i want to select the username whos taking course 1 AND 3 , not at least 1 or 3 , i mean both 1 and 3 我想选择参加课程1和3的用户名,而不是至少1或3,我的意思是1和3

i've tried the following mysql queries 我尝试了以下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 ;

the first and third queries executed with no results shown , and the second one show all users who had at least course_id 1 or 3 执行的第一个和第三个查询没有显示结果,第二个查询显示的所有用户至少具有course_id 1或3

if you are wondering why am i using the LEFT JOIN , this is because i need to join table's results , and the above line of code is just an example , and im using to get data from about 9 tables using the LEFT join . 如果您想知道为什么要使用LEFT JOIN,这是因为我需要联接表的结果,而上面的代码行只是一个示例,即时通讯使用LEFT join从大约9个表中获取数据。

any help please ? 请帮忙吗? thanks 谢谢

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 ";

this show me the result i want , its output "def" , but i can't use the user_id as a static value ( number 2 in this example ) 这向我显示了我想要的结果,其输出为“ def”,但是我不能使用user_id作为静态值(在此示例中为2)

This problem is called Relational Division 这个问题叫做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

If course_ID is not unique for every users considering that the user have retake the course, a DISTINCT keyword is needed to coung unique courses, 如果考虑到该用户已重修课程,并不是每个用户的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

OUTPUT OUTPUT

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

please try this: 请尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM