如果有一个或多个owner_ids
(例如,2,4和6),我想通过resources.id
返回与owners
关联的owners_has_resources
列表。没问题,我可以做SELECT DISTINCT ohr.resources_id FROM owners_has_resources ohr WHERE ohr.owners_id IN (2,4,6);
现在我被困住了。我想返回与上面相同的resources.id
列表,但排除任何也链接到未删除链接的所有者(由owners.deleted!=true
确定),其中链接未被删除(由owners_has_resources.deleted!=true
)
对于所有最初提供的owners.deleted
(即2,4,6),可以假设true
为owners_ids
例如,给定owners_ids
2和4,我应该返回resources_id
2和3.请注意,我的意思是说deleted=TRUE
表示它已被删除,但由于答案已经发布使用前面的,我不会编辑问题。相反,下面的真值表显示owner_not_deleted
和resource_not_deleted
。
+-----------+-------------------+--------------+----------------------+
| owners_id | owner_not_deleted | resources_id | resource_not_deleted |
+-----------+-------------------+--------------+----------------------+
| 2 | FALSE | 1 | TRUE |
| 2 | FALSE | 2 | TRUE |
| 4 | FALSE | 2 | TRUE |
| 4 | FALSE | 3 | TRUE |
| 5 | TRUE | 1 | FALSE |
| 5 | TRUE | 2 | TRUE |
| 7 | TRUE | 2 | FALSE |
+-----------+-------------------+--------------+----------------------+
owners
- id (INT PK)
- name, etc
- deleted (true/false)
resources
- id (INT PK)
- name, etc
owners_has_resources
- owners_id (INT PK REFERENCES owners.id)
- resources_id (INT PK REFERENCES resources.id)
- deleted (true/false)
答案 0 :(得分:0)
怎么样?
SELECT DISTINCT ohr.resources_id
FROM owners_has_resources ohr
JOIN owners o ON ohr.owners_id = o.id
WHERE ohr.owners_id IN (2,4,6)
AND (o.deleted = FALSE OR ohr.deleted = FALSE);
答案 1 :(得分:0)
首先,您选择所需的数据,然后只选择NOT EXISTS
块中未被删除的所有者引用的数据
SELECT DISTINCT ohr.resources_id
FROM owners_has_resources ohr
JOIN owners o ON ohr.owners_id = o.id
WHERE ohr.owners_id IN (2,4,6)
AND NOT EXISTS (
SELECT NULL FROM owners_has_resources ohr2
JOIN owners o2 ON ohr2.owners_id = o2.id
WHERE ohr2.deleted=FALSE
AND o2.deleted=FALSE
AND ohr.resources_id=ohr2.resources_id
)
答案 2 :(得分:0)
SELECT DISTINCT ohr1.resources_id
FROM owners_has_resources ohr1
LEFT OUTER JOIN owners_has_resources ohr2 ON ohr2.resources_id=ohr1.resources_id AND ohr2.deleted = TRUE
LEFT OUTER JOIN owners o ON o.id=ohr2.owners_id AND ohr2.deleted = TRUE
WHERE ohr1.owners_id IN (2,4,6) AND o.id IS NULL;
或
SELECT DISTINCT ohr1.resources_id
FROM owners_has_resources ohr1
LEFT OUTER JOIN owners_has_resources ohr2 ON ohr2.resources_id=ohr1.resources_id
LEFT OUTER JOIN owners o ON o.id=ohr2.owners_id
WHERE ohr1.owners_id IN (2,4,6) AND o.id IS NULL AND ohr2.deleted = TRUE AND ohr2.deleted = TRUE;
对于一种方法是否优于另一种方法,我将不胜感激。