我有一个contents
表。
+------------+------+----------+
| content_id | year | has_file |
+------------+------+----------+
| 1 | 2017 | true |
| 2 | 2018 | true |
| 3 | 2016 | true |
| 4 | 2018 | true |
| 5 | 2018 | false |
+------------+------+----------+
然后我有uploads
表。
+----+------------+------------+
| id | content_id | filename |
+----+------------+------------+
| 1 | 2 | sample.jpg |
+----+------------+------------+
我想根据最近的年份来获取数据,然后再获取是否有文件。
我可以使用查询SELECT * FROM contents ORDER BY year DESC, has_file DESC
来做到这一点。
问题不是has_file
设置为true
的所有记录实际上都记录在uploads
表上。
通过添加WHERE EXISTS (SELECT 1 FROM uploads WHERE uploads.content_id = contents.content_id)
,可以排除另一个表上不存在的所有记录。
但是我不想排除它,我只是希望它出现在最后,而带有文件的记录首先出现。这可能吗?
预期结果:
+------------+------+----------+
| content_id | year | has_file |
+------------+------+----------+
| 2 | 2018 | true |
| 4 | 2018 | true |
| 5 | 2018 | false |
| 1 | 2017 | true |
| 3 | 2016 | true |
+------------+------+----------+
答案 0 :(得分:7)
只需将EXISTS
子句添加到查询的ORDER BY
子句中即可:
SELECT *
FROM contents
ORDER BY year DESC,
has_file DESC,
EXISTS (SELECT 1 FROM uploads WHERE uploads.content_id = contents.content_id) DESC
输出:
content_id year has_file
2 2018 true
4 2018 true
5 2018 false
1 2017 true
3 2016 true
答案 1 :(得分:1)
您也可以使用它,
SELECT
id, year, has_file
FROM
(SELECT
c.id,
c.year,
c.has_file,
CASE
WHEN u.id IS NOT NULL THEN 1
ELSE 2
END AS flag
FROM
contents c
LEFT JOIN uploads u ON (c.id = u.content_id)) tmp
ORDER BY flag , year DESC;