GROUP BY in mysql 以 IS NULL 列为条件

GROUP BY in mysql conditional on IS NULL column

我很难找到使用 GROUP BY 消除这些结果中多余行的正确方法:

id  title               author  city        year    pageId  page
1   The Faraway Tree    Blyton  New York    1951    NULL    1
1   The Faraway Tree    Blyton  New York    1951    NULL    2
1   The Faraway Tree    Blyton  New York    1951    NULL    3
1   The Faraway Tree    Blyton  New York    1951    NULL    4
1   The Faraway Tree    Blyton  New York    1951    NULL    5
1   The Faraway Tree    Blyton  New York    1951    NULL    7
1   The Faraway Tree    Blyton  New York    1951    NULL    9
1   The Faraway Tree    Blyton  New York    1951    NULL    13
1   The Faraway Tree    Blyton  New York    1951    NULL    30
2   Winnie the Pooh     Milne   London      1937    NULL    76
2   Winnie the Pooh     Milne   London      1937    NULL    73
2   Winnie the Pooh     Milne   London      1937    NULL    74
2   Winnie the Pooh     Milne   London      1937    NULL    75
1   The Faraway Tree    Blyton  New York    1951    4       32
2   Winnie the Pooh     Milne   London      1937    6       74

我想做的只是消除重复项,但前提是 pageId 为 NULL。

id  title               author  city        year    pageId  page
1   The Faraway Tree    Blyton  New York    1951    NULL    1
2   Winnie the Pooh     Milne   London      1937    NULL    76
1   The Faraway Tree    Blyton  New York    1951    4       32
2   Winnie the Pooh     Milne   London      1937    6       74

用简单的英语来说,逻辑是,如果 pageId 为 NULL,则按标题分组,否则将单行分开

听起来很简单,但无论我使用什么聚合函数或 GROUP BY 修饰符,我要么得到语法错误,要么得到不正确的结果(通常是 pageId 得到的行与 NULL pageIds 分组)。

请注意,当 pageId 返回 NULL 时,"page" 列对我来说变得不重要。

这是我正在使用的 SQL 查询(MySQL v. 5.6.37):

SELECT id,title,author,city,`year`,NULL as pageId,pageNum as page 
FROM titles
WHERE id IN ([complex subquery])
UNION ALL (
    SELECT id,title,author,city,`year`,pageId,pageNum 
    FROM titles 
    WHERE titles.t_id IN ([complex subquery])
    )

这个问题我已经卡了三天了,在SO或者网上都找不到准确的解决办法。我想是时候谦虚地请求你的帮助了。请。

像这样的东西应该可以工作:

SELECT id, title, author, city, `year`, NULL AS pageId, MIN(page) as page 
FROM title
WHERE pageId IS NULL
GROUP BY id, title, author, city, `year`

UNION ALL

SELECT id, title, author, city, `year`, pageId, page 
FROM title
WHERE pageId IS NOT NULL;

Demo here

null pageId 转换为 0 有点棘手,然后按它分组:

select
    case when pageId is null then 0 else pageId end,
    id,title,author,city,`year`, page
from titles
group by 1, id,title,author,city,`year`, page

如果你使用 IFNULL(pageId, 0) 然后在 groupd by 中使用这个伪列会怎么样? 喜欢:
SELECT id,title,author,city,year,IFNULL(pageId, 0) as pageId, pageNum as page FROM titles WHERE id IN ([complex subquery]) group by title, pageId;
您可以在 IFNULL 中输入任何值而不是 0 - 'none' 也可以。