我以前有1列country
,在其上面我执行了COUNT(DISTINCT())
和GROUP_CONCAT(DISTINCT())
。
SELECT
(SELECT COUNT(DISTINCT(country)) FROM flagevent AS f2
WHERE f2.user = f.user
) AS totalflags,
GROUP_CONCAT(DISTINCT(country) ORDER BY c.name) AS allcountries,
f.user, u.username
FROM flagevent AS f
INNER JOIN country AS c ON f.country = c.code
INNER JOIN user AS u ON f.user = u.id
WHERE f.user = 1
OR f.user in (1, 2, 3)
GROUP BY user
ORDER BY totalflags DESC;
这将为我提供示例结果:
totalflags | allcountries | user | username
---------------------------------------------
5 | es,fr,it,de,pt | 1 | jagomf
现在代替原来的country
列了,我有2列 country1
和country2
,我必须在它们上面执行相同的计算,得到{{ 1}}都是两列的值。
如何在两个列的不同数据之上应用相同的DISTINCT
和COUNT()
?
更新:表架构:
GROUP_CONCAT()
答案 0 :(得分:0)
这是简单的方法-只需将新的更改为旧的样子即可:
请注意,由于您对子查询进行了计数,因此已对其进行了修改以使用CTE。
WITH flagevent_comb as (
SELECT user, country, COUNT(DISTINCT country) as cnt
FROM (
SELECT user, country1 AS country FROM flagevent WHERE country1 IS NOT NULL
UNION ALL
SELECT user, country2 AS country FROM flagevent WHERE country2 IS NOT NULL
) x
GROUP BY user, country
)
SELECT f.cnt as totalflags,
GROUP_CONCAT(DISTINCT(country) ORDER BY c.name) AS allcountries,
f.user, u.username
FROM flagevent_comb AS f
INNER JOIN country AS c ON f.country = c.code
INNER JOIN user AS u ON f.user = u.id
WHERE f.user = 1
OR f.user in (1, 2, 3)
GROUP BY user
ORDER BY totalflags DESC;
请注意,您可能必须使子查询更加复杂。例如,如果有时country1或country2为null,则可能会更好。
SELECT user, country1 AS country FROM flagevent WHERE country1 IS NOT NULL
UNION ALL
SELECT user, country2 AS country FROM flagevent WHERE country2 IS NOT NULL
其他业务规则可能适用。