Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php mysql选择多任务-连接_Php_Mysql_Sql_Relational Division - Fatal编程技术网

Php mysql选择多任务-连接

Php mysql选择多任务-连接,php,mysql,sql,relational-division,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 我尝试了以下mysq

假设我有以下表格

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 ;
第一个和第三个查询执行时没有显示结果,第二个查询显示至少拥有课程id 1或3的所有用户

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

需要帮忙吗?谢谢

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”,
但是我不能将用户id用作静态值(本例中的数字2)

这个问题称为
关系分割

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
如果
课程\u 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      ║
╚════╩══════════╝
请试试这个:

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