我必须根据他们的AniDB ID对我的动漫索引进行分组,并根据文件自动增量ID以DESCENDING顺序显示值。
以下是我目前所做的事情:
SELECT
f.id, f.category, f.anidb, f.mal_id, COUNT( * ) AS dupes, f.filename,
a.titles, a.synopsis, a.episodes, a.image, a.rating,
c.name as cat_name, c.id as categoryid
FROM table_files f
LEFT JOIN table_anidb a ON a.id = f.anidb
LEFT JOIN table_categories c ON c.id = f.category
GROUP BY a.id ORDER BY f.id DESC
我有火影忍者8集。第8集的ID是204.而ep.1的ID是160.查询返回如下:
id | anidb | filename | dupes | cat_name
--------------------------------------------------------
201 | 8692 | SAO | 1 | Series
200 | 9251 | RYO | 1 | Movie
.....
.......
160 | 239 | Naruto ep.1 | 8 | Series
但是我希望火影忍者第8集显示在结果的顶部,而不是最后的第1集。
如何使用OR
逻辑同时按anidb和mal_id进行分组?因此,即使没有提供任何anidb ID,也可以进行分组。
答案 0 :(得分:2)
广告。 1。
由于id
,anidb
和filename
都在一个表中,我担心您无法远离子查询加入:
<强> SQLFiddle 强>
SELECT f.id, f.anidb, f.filename
FROM files f
JOIN
(SELECT MAX(id) as id FROM files GROUP BY anidb) AS f2
ON f2.id = f.id
ORDER BY f.id DESC
(数据为了可读性而扁平,但你可以得到一般的想法)
广告。 2。
至于第二个问题,你真的只需要在上面加入的子查询中添加第二个分组列:
<强> SQLFiddle 强>
SELECT f.id, f.anidb, f.mal_id, f.filename
FROM files f
JOIN
(SELECT MAX(id) as id FROM files GROUP BY anidb, mal_id) AS f2 on f2.id = f.id
ORDER BY f.id DESC
NULL
彼此不同(例如NULL!= NULL),因此不必担心分组会将所有已归零的anidb
行融为一体。
答案 1 :(得分:0)
对于第一个问题,您可以使用ORDER BY dupes
SELECT
f.id, f.category, f.anidb, f.mal_id, COUNT( * ) AS dupes, f.filename,
a.titles, a.synopsis, a.episodes, a.image, a.rating,
c.name as cat_name, c.id as categoryid
FROM table_files f
LEFT JOIN table_anidb a ON a.id = f.anidb
LEFT JOIN table_categories c ON c.id = f.category
GROUP BY a.id ORDER BY dupes DESC
对于第二个问题,您可以使用CASE
检查f.anidb
是否为空
SELECT
f.id, f.category, f.anidb, f.mal_id, COUNT( * ) AS dupes, f.filename,
a.titles, a.synopsis, a.episodes, a.image, a.rating,
c.name as cat_name, c.id as categoryid
FROM table_files f
LEFT JOIN table_anidb a ON a.id = f.anidb
LEFT JOIN table_categories c ON c.id = f.category
GROUP BY
(CASE WHEN f.anidb IS NULL THEN f.mal_id ELSE f.anidb END )
ORDER BY dupes DESC