MySql内连接和" OR"如果值等于0

时间:2015-10-14 00:04:32

标签: c# mysql join

所以我有这个内部联接

SELECT IDEvent,events.IDSubject,events.month,events.year
FROM events
    INNER JOIN subjects ON events.IDSubject = subjects.IDSubject
    INNER JOIN classes ON subjects.IDClass = classes.IDClass
    INNER JOIN students ON classes.IDClass = students.IDClass
WHERE events.month=10
    AND events.year=2015
    AND (students.DNI=DNI OR events.IDSubject='0')`

我想要做的是根据用户IDSubject选择所有事件,也许如果IDSubject = 0也有一些事件,我可以得到那些取决于用户的事件,但是不能得到IDSubject = 0的那些,有没有人知道如何正确地做到这一点?

我的数据库模型,如果有人需要看到它

2 个答案:

答案 0 :(得分:1)

SELECT IDEvent,events.IDSubject,events.month,events.year
FROM events
      INNER JOIN subjects ON events.IDSubject = subjects.IDSubject
      INNER JOIN classes ON subjects.IDClass = classes.IDClass
      INNER JOIN students ON classes.IDClass = students.IDClass
WHERE events.month=10
      AND events.year=2015
      AND students.DNI=DNI
UNION SELECT IDEvent, events.IDSubject ,events.month ,events.year
      FROM events WHERE IDSubject='0'

答案 1 :(得分:0)

如果我已经正确理解,你想要所有具有匹配主题的事件,或者让subjectid = 0(我猜不会在主题表中存在)。

SELECT IDEvent
, events.IDSubject
,events.month
,events.year
FROM events
LEFT OUTER JOIN subjects ON events.IDSubject = subjects.IDSubject
INNER JOIN classes ON subjects.IDClass = classes.IDClass
INNER JOIN students ON classes.IDClass = students.IDClass
WHERE (events.IDSubject = 0 OR subjects.IDSubject is not null)
AND events.month = 10
AND events.year = 2015
AND (students.DNI = DNI OR events.IDSubject = 0)