如何从表A中获取表B中没有特定状态的等价物的记录?

时间:2011-11-07 16:46:53

标签: mysql

UPDATE 根据以下@BrianFisher的回答,我试过了:

SELECT np.id AS people_id, np.first_name, np.last_name, ur.rid
FROM new_people np
LEFT JOIN institute.users_roles ur ON np.institute_uid = ur.uid
AND ur.rid =8
LEFT JOIN roster r ON np.id = r.people_id
WHERE np.company_id =1
AND np.active =1
AND (r.roster_id IS NULL OR NOT (r.status =  'pending' OR r.status =  'submitted'))
ORDER BY np.last_name, np.first_name

似乎 工作;它确实返回了我想要的东西。任何人都可以告诉我它是否有理由不起作用,或者可能无法使用更大的数据集? (也就是说,这次它是否巧合?将语句嵌入AND中是不是很糟糕?)

===================================

SELECT np.id AS people_id, np.first_name, np.last_name, ur.rid
FROM new_people np
LEFT JOIN institute.users_roles ur ON np.institute_uid = ur.uid
AND ur.rid =8

LEFT JOIN roster r ON np.id = r.people_id
WHERE np.company_id =1
AND np.active =1
AND NOT (
r.status =  'pending'
OR r.status =  'submitted'
)
ORDER BY np.last_name, np.first_name

编辑 - 我也尝试过这样的查询,结果相同:

SELECT np.id AS people_id, np.first_name, np.last_name, ur.rid
FROM new_people np
LEFT JOIN institute.users_roles ur ON np.institute_uid = ur.uid
AND ur.rid =8

LEFT JOIN roster r ON np.id = r.people_id AND NOT (r.status =  'pending'
OR r.status =  'submitted')

WHERE np.company_id =1
AND np.active =1

ORDER BY np.last_name, np.first_name

new_people:
id      first_name      last_name   institute_uid   company_id
==      ==========      =========   =============   ==========
1       Tester          Jones       100             1
2       Tester          Smith       200             1
3       Tester          Brown       300             1
4       Tester          White       400             1

users_roles:
uid    rid
===    ===
100    8
200    8
300    8
400    8

roster:
roster_id   people_id   company_id   status
=========   =========   ==========   ======
8           1           1            completed
15          2           1            submitted
23          3           1            pending

我希望此查询返回的是Tester Jones(people_id 1)的记录,因为他的名单记录不是待处理或提交的,而Tester White,因为他根本没有名单记录。该查询返回Tester Jones,但不返回Tester White。我如何让它包含new_people表中的某个人,因为他们在名单表中没有记录?我已经在名单桌上尝试过JOIN,LEFT JOIN,RIGHT JOIN,INNER JOIN;他们都回报了同样的事情。

1 个答案:

答案 0 :(得分:0)

尝试

SELECT np.id AS people_id, np.first_name, np.last_name, ur.rid
FROM new_people np
LEFT JOIN institute.users_roles ur ON np.institute_uid = ur.uid
AND ur.rid =8

LEFT JOIN roster r ON np.id = r.people_id 

WHERE np.company_id =1
AND np.active =1
AND (r.roster_id IS NULL OR r.status =  'pending' OR r.status =  'submitted')

ORDER BY np.last_name, np.first_name