我有三张桌子: 1个日期 - 包含列日期 2本书 - 包含栏目房间,日期和姓氏 3人 - 包含姓氏
我可以在日期范围内的特定日期获得房间内有人的日期。
SELECT date, IFNULL(surname, 'ghost')
FROM book JOIN dates ON book.date=dates.date JOIN people ON people.surname=book.surname
WHERE room = 113
AND date BETWEEN '2015-01-01' AND '2015-01-07'
+------------+-----------+
| Date | Surname |
+------------+-----------+
| 2015-01-02 | Surname 1 |
| 2015-01-05 | Surname 2 |
+------------+-----------+
如何返回完整的日期列表,包括房间内没有人的日期,以便打印出给定范围内的每个日期,如果指定房间内没有人,则会打印“幽灵”?
答案 0 :(得分:0)
您需要使用LEFT JOIN
SELECT dates.date, IFNULL(book.surname, 'ghost')
FROM dates
LEFT JOIN book
ON book.date=dates.date
AND book.room = 113
-- LEFT JOIN people ON people.surname=book.surname
WHERE dates.date BETWEEN '2015-01-01' AND '2015-01-07'
请注意book.room = 113
必须在ON子句中。在WHERE子句中使用它会将LEFT JOIN转换为INNER JOIN。