我很难检索数据。
人
PId | Name
---------------
1 | David
2 | Steven
3 | John
PersonDays
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的人员中检索记录。
所以,大卫和史蒂文是正确的答案。
如何在MySQL中编写查询?
日值是动态的。
答案 0 :(得分:2)
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
答案 1 :(得分:0)
你可以试试这个
select * from Persons where PId in (
select PId from PersonDays where Days in (1,2,3)) as P
where P.PId = Persons.PId;
答案 2 :(得分:0)
<强> SQL FIDDLE 强>
<强> QUERY 强>
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%'
希望这会对你有帮助......!