Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.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
Mysql 选择一个表中的记录,该记录在另一个表中必须有某些行_Mysql_Sql - Fatal编程技术网

Mysql 选择一个表中的记录,该记录在另一个表中必须有某些行

Mysql 选择一个表中的记录,该记录在另一个表中必须有某些行,mysql,sql,Mysql,Sql,我检索数据有困难 人 PId | Name --------------- 1 | David 2 | Steven 3 | John 个人日 PId | Days --------------- 1 | 0 1 | 1 1 | 2 1 | 3 2 | 1 2 | 2 2 | 3 2 | 4 3 | 0 3 | 1 3 | 4 我想从PersonDays表中的Day值为1,2,3的Person中检索记录 因此,大卫和史蒂文是正确的答案

我检索数据有困难

PId | Name
---------------
1   | David
2   | Steven
3   | John
个人日

PId | Days
---------------
1   | 0
1   | 1
1   | 2
1   | 3
2   | 1
2   | 2
2   | 3
2   | 4
3   | 0
3   | 1
3   | 4
我想从PersonDays表中的Day值为1,2,3的Person中检索记录

因此,大卫和史蒂文是正确的答案

如何在MySQL中编写查询

编辑 日值是动态的

select distinct p.* 
from persons p 
     join PersonDays pd on p.PId=pd.PId and pd.Days in (1,2,3)
更新

SELECT p.PId, p.name,COUNT(pd.PId) AS days_count 
FROM Persons p 
INNER JOIN PersonDays pd on p.PId=pd.PId and pd.Days in (1,2,3)
GROUP BY p.PId
HAVING days_count=3
你可以试试这个

select * from Persons where PId  in (
select PId  from PersonDays where Days in (1,2,3)) as P 
where P.PId = Persons.PId;

查询

SELECT p.name AS 'Person Name'
FROM `person` AS p
JOIN (SELECT p.pid AS 'pid',GROUP_CONCAT(pd.days) AS 'days'
FROM `person` AS p
JOIN `persondays` AS pd ON p.pid = pd.pid
GROUP BY p.pid) AS sub ON sub.pid = p.pid
WHERE sub.days LIKE '%1%2%3%'

希望这能帮助你

可能的副本,这不也会返回约翰吗?他有第1天,但没有第2天和第3天。这也会让约翰得到回报,但事实并非如此required@Barmar我改进了查询以使用所有的日期,他想要的是那些拥有全部3天的人,而不是3天中的任何一天。此查询将返回John,这不是预期的结果。