我对MySQL很新,我在尝试将一些查询合并为一个查询时遇到了一些问题。基本上我有两张桌子:
我需要得到:
Jobs
------------------
IDJob - The PKey
JobInfo - Some Data
JobPosition
------------------
PositionID - Each Job can have multiple positions
JobID - Value from Jobs Table
StaffID - Value from Staffs Table
Status - Status of Staff for the Job
我正在尝试获取所有IDJobs WHERE
(
SELECT JobID AS IDJob
FROM SelectedStaff
WHERE StaffID <>10
)
UNION
(
SELECT IDJob
FROM Jobs
WHERE IDJob
IN (
SELECT JobID
FROM SelectedStaff
WHERE SelectStatus
IN ( 1, 6 )
AND StaffID =10
)
)
但结果并没有为我返回工作人员不在其中的工作ID。这将是更大的列表,然后使用较小的查询过滤它。
任何帮助都将不胜感激。
编辑:
示例数据将是:
Jobs Table
IDJob JobInfo
1 Job1
2 Job2
3 Job3
JobPosition
PositionID JobID StaffID Status
1 2 10 0
2 2 10 6
3 3 10 0
这应该导致:
IDJob
1
2
答案 0 :(得分:0)
这是你想要的吗?
select jp.JobId
from JobPosition jp
group by jp.JobId
having sum(StaffId = 10) = 0 or -- Staff10 is not part of the job
sum(StaffId = 10 and status in (1, 6)) > 0
这使用where
子句中的条件聚合来计算与每个条件匹配的行数。
答案 1 :(得分:0)
所以这是最终适合我的解决方案。我不知道我是否过于复杂,但这是正确的结果:
(
SELECT IDJob
FROM Jobs
WHERE IDJob
NOT IN (
SELECT JobID AS IDJob
FROM JobPosition
WHERE StaffID = 10
)
)
UNION
(
SELECT IDJob
FROM Jobs
WHERE IDJob
IN (
SELECT JobID
FROM SelectedStaff
WHERE JobPosition IN (1,6)
AND StaffID=10
)
)