【发布时间】:2018-05-25 02:46:32
【问题描述】:
我很难找出使用 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 或 Web 上找不到准确的解决方案。我想是时候谦虚地请求你的帮助了。请。
【问题讨论】:
标签: mysql group-by conditional