说我有下表:医生和工作日:
DocNumbers | idNum
118 | 11
119 | 12
120 | 13
121 | 14
122 | 15
注意:医生可以在几个不同的工作日工作。
DocNum | Workday |AmountOfHours |
118 | 1 | 8 |
118 | 3 | 9 |
120 | 1 | 6 |
121 | 3 | 5 |
122 | 4 | 7 |
我想创建一个新表,其中包含在第1天和第3天工作的所有医生的ID - 这意味着我将获得一个仅包含118的表。
到目前为止我已经:
SELECT distinct Doctors.doctorNumber, idNum
FROM Doctors, Workdays
WHERE Workdays.dayInWeek in (1,3)
AND Workdays.doctorNumber=Doctors.doctorNumber
但似乎我得到的结果与120和121无关。 所以'IN'更像是'OR'。似乎找不到'和'的等价?
答案 0 :(得分:2)
如果您加入Workdays表两次,这很容易,每天要检查一次:
select Doctors.DocNumbers, Doctors.idNum
from Doctors
inner join Workdays as Workdays1 on Workdays1.DocNum = Doctors.DocNumbers and Workdays1.Workday = 1
inner join Workdays as Workdays3 on Workdays3.DocNum = Doctors.DocNumbers and Workdays3.Workday = 3;
答案 1 :(得分:0)
使用简单连接尝试此操作
SELECT DISTINCT w.`DocNum`, d.idNum
FROM doctors d
LEFT JOIN Workdays w ON(d.`DocNumbers`=w.`DocNum`)
LEFT JOIN Workdays ww ON(d.`DocNumbers`=ww.`DocNum`)
WHERE w.`Workday` = 1 AND ww.`Workday` =3
这是另一种做同样的方式
SELECT w.`DocNum`, d.idNum
FROM doctors d
LEFT JOIN Workdays w ON(d.`DocNumbers`=w.`DocNum`)
GROUP BY d.`DocNumbers`
HAVING GROUP_CONCAT(w.`Workday` SEPARATOR ',')= '1,3'