我正在尝试为以下搜索情况建立一个SQL语句:
我一直在尝试根据表B中状态列的值,返回表A中个人记录的所有列。表A中的每个记录都可能在表B中有多个行,这使得它成为一对多关系。状态列是可为空的,具有整数数据类型。
以下是表B中状态的可能取值:
- NULL = Pending,
- 1 = Approved,
- 2 = Denied,
- 6 = Forced Approval,
- 7 = Forced Denial
最终用户可以在以下场景中进行搜索:
- Approved - All table B records must have a value of 1 or 6 for status.
- Denied - One table B record must have a value of 2 or 5. Any other records can have 1,6, or null.
- Pending - All table B records can have a value of 1,6 or null. One record must be null because it is not considered completed.
UPDATE
I consulted with one of our DBAs and he developed the following solution:
批准。
SELECT a.* FROM TableA a INNER JOIN TableB ON b.id = a.id
WHERE
(b.status in (1,6) and b.status IS NOT NULL) AND
b.id NOT IN (SELECT id from TableB WHERE status IS NULL)
AND b.id NOT IN (SELECT id from TableB WHERE status in (2,7))
被拒绝:
SELECT a.* FROM TableA a INNER JOIN TableB ON b.id = a.id
WHERE
(b.status in (2,7))
待定
SELECT a.* FROM TableA a INNER JOIN TableB ON b.id = a.id
WHERE
(b.status IN (1,6) OR b.status IS NULL)
AND b.id NOT IN (SELECT b.id FROM TableA a INNER JOIN TableB b ON b.id = a.id WHERE (b.status IN (1,6) AND b.status IS NOT NULL) AND b.id NOT IN (SELECT id from TableB WHERE status IS NULL))
AND b.id NOT IN (SELECT id FROM TableB WHERE status IN (2,7))
UPDATE 2:
@Micth Wheat - How would I refactor the following solution using the EXIST/NOT EXIST t-sql keyword?