我们拥有多对多关系中的数据,我们的每个成员都可以选择他们正在学习的科目。此数据使用软删除模式,其中DATETIME archived
字段保留NULL
,直到数据被视为已删除为止。
我们想要做的是选择用户当前未订阅的主题,忽略他们当前订阅的主题。
这是表结构:
`member`
- id
- name
- created
- updated
- archived
`subject`
- id
- name
- created
- updated
- archived
`member_subject`
- member_id
- subject_id
- created
- archived
我们的基本查询结构是:
SELECT DISTINCT subject.*
FROM subject
LEFT JOIN member_subject ON member_subject.subject_id = subject.id
WHERE subject.archived IS NULL
# Not sure how to go about the rest of the WHERE clause here
ORDER BY subject.name
答案 0 :(得分:0)
尝试此查询 -
SELECT s.id
FROM subject s
LEFT JOIN member_subject ms
ON ms.subject_id = s.id
GROUP BY s.id
HAVING COUNT(ms.subject_id) = 0
...添加您需要的其他WHERE过滤器。
答案 1 :(得分:0)
这将为当前未订阅的每个用户生成所有主题
SELECT d.*, e.*
FROM
(
SELECT a.ID memberID, b.ID SubjectID
FROM member a, subject b
) c
INNER JOIN member d
ON c.memberID = d.ID
INNER JOIN Subject e
ON c.SubjectID = e.ID
LEFT JOIN member_subject f
ON c.memberID = f.member_ID AND
c.SubjectID = f.subject_ID
WHERE f.member_ID IS NULL
-- AND d.ID = '' -- <<== for specific userID