基于自动增量列的ORDER的Mysql GROUPing

时间:2013-12-14 12:44:09

标签: mysql

我必须根据他们的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

问题:

  1. 我有火影忍者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集

  2. 如何使用OR逻辑同时按anidb和mal_id进行分组?因此,即使没有提供任何anidb ID,也可以进行分组。

2 个答案:

答案 0 :(得分:2)

广告。 1。

由于idanidbfilename都在一个表中,我担心您无法远离子查询加入:

<强> 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