我有这个 SQL:
SELECT
c.name AS category_name,
a.name,
a.path,
a.extension,
a.width,
a.height,
a.server
FROM categories c
JOIN news_categories nc ON nc.categories_id = c.id
JOIN news_attachments na ON nc.news_id = na.news_id
JOIN attachments a ON na.attachments_id = a.id
WHERE na.cover = 1
ORDER BY nc.news_id DESC
它向我显示了正确的结果
+---------------+------------+---------------------+-----------+-------+--------+--------+
| category_name | name | path | extension | width | height | server |
+---------------+------------+---------------------+-----------+-------+--------+--------+
| Игры | c54950f283 | a6f00bcd/b25/cfaf2e | jpg | 450 | 416 | 1 |
| Игры | fa4249e534 | a6f00bcd/b89/cfaf2e | jpg | 400 | 250 | 1 |
| Игры | d7b009eeb7 | a6f00bcd/bfa/cfaf2e | jpg | 200 | 140 | 1 |
| Игры | 143cb7a38d | a6f00bcd/baa/cfaf2e | jpg | 200 | 140 | 1 |
| Игры | a70451eca7 | a6f00bcd/bc6/cfaf2e | jpg | 200 | 140 | 1 |
| Игры | 3ab8a0c051 | a6f00bcd/b5b/cfaf2e | jpg | 200 | 140 | 1 |
| Игры | 206255a07a | a6f00bcd/b98/cfaf2e | jpg | 200 | 140 | 1 |
| Игры | 86ef53ee1f | a6f00bcd/b93/cfaf2e | jpg | 200 | 140 | 1 |
| Игры | a50367f861 | a6f00bcd/b32/cfaf2e | jpg | 200 | 140 | 1 |
| Игры | dcfdd990c6 | a6f00bcd/b32/cfaf2e | jpg | 200 | 140 | 1 |
| Игры | 5a3df9f4ad | a6f00bcd/b34/cfaf2e | jpg | 200 | 140 | 1 |
| Игры | fb3ba0390d | a6f00bcd/b35/cfaf2e | jpg | 200 | 140 | 1 |
| Игры | 0e31ef118d | a6f00bcd/be5/cfaf2e | jpg | 457 | 249 | 1 |
| Игры | 82d41d9d62 | a6f00bcd/b97/cfaf2e | jpg | 457 | 249 | 1 |
+---------------+------------+---------------------+-----------+-------+--------+--------+
但是如果我们添加GROUP BY
,那么它会显示没有顺序的结果
SELECT
c.name AS category_name,
a.name,
a.path,
a.extension,
a.width,
a.height,
a.server
FROM categories c
JOIN news_categories nc ON nc.categories_id = c.id
JOIN news_attachments na ON nc.news_id = na.news_id
JOIN attachments a ON na.attachments_id = a.id
WHERE na.cover = 1
GROUP BY c.id ORDER BY nc.news_id DESC
然后结果将是
+---------------+------------+---------------------+-----------+-------+--------+--------+
| category_name | name | path | extension | width | height | server |
+---------------+------------+---------------------+-----------+-------+--------+--------+
| Игры | 82d41d9d62 | a6f00bcd/b97/cfaf2e | jpg | 457 | 249 | 1 |
+---------------+------------+---------------------+-----------+-------+--------+--------+
但是应该是这样的
+---------------+------------+---------------------+-----------+-------+--------+--------+
| category_name | name | path | extension | width | height | server |
+---------------+------------+---------------------+-----------+-------+--------+--------+
| Игры | c54950f283 | a6f00bcd/b25/cfaf2e | jpg | 450 | 416 | 1 |
+---------------+------------+---------------------+-----------+-------+--------+--------+
它的错误在哪里?