订单记录(如果在另一个表中)

时间:2018-10-04 06:42:49

标签: mysql sql

我有一个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     |
+------------+------+----------+

2 个答案:

答案 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

SQLFiddle Demo

答案 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;