0

我们拥有多对多关系的数据,我们的每个成员都可以选择他们正在学习的主题。此数据使用软删除模式,其中 DATETIMEarchived字段一直保留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
4

2 回答 2

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
于 2013-01-29T07:28:06.543 回答
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 过滤器。

于 2013-01-29T07:23:33.980 回答