mariadb UNION查询表中的每个原始数据

xxe27gdn  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(190)

mariaDB的版本我有一个表:
| 用户|动物|
| --|--|
| 1 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
| 1 | 2 |
| 3 | 2 |
| 4 | 2 |
| 5 | 2 |
| 2 | 1 |
| 5 | 7 |
| 2 | 2 |
| 5 | 8 |
| 2 | 9 |
| 5 | 9 |
| 4 | 10 |
| 5 | 10 |
我想计算用户1与其他用户的UNION集。例如,用户2设置为= 3,因为用户1
| 用户|动物|
| --|--|
| 1 | 1 |
| 1 | 2 |
user 2有
| 用户|动物|
| --|--|
| 2 | 1 |
| 2 | 2 |
| 2 | 9 |
在理论中,可以这样做

WITh user1_user2 AS (
SELECT * FROM user_categories
WHERE user_id = 1
UNION
SELECT * FROM user_categories
WHERE user_id = 2),
user1_user3 AS(
SELECT * FROM user_categories
WHERE user_id = 1
UNION
SELECT * FROM user_categories
WHERE user_id = 2)

字符串
但是有很多用户
FOR(1,1),(1,2),(1,3),(1,4),(1,5)

(2,7),(2,8),(2,9),
(3,1),(3,2),(3,3),(3,4),(3,5),(3,6),
(4,1),(4,2),(4,10),
(5,1),(5,2),(5,3),(5,4),(5,5),(5,6),(5,7),(5,8),(5,9),(5,10);
应该是这样的:
2 | 8
3 | 6
4 | 6
5 | 10

qni6mghb

qni6mghb1#

您可以计算每个用户的动物数量,排除用户1已经拥有的动物,然后将两者相加:

SELECT u.user, COUNT(uc.animal) + (SELECT COUNT(*) FROM user_categories WHERE user = 1) AS cnt
FROM (SELECT DISTINCT user FROM user_categories WHERE user <> 1) u
LEFT JOIN user_categories uc
    ON u.user = uc.user
   AND animal NOT IN (SELECT animal FROM user_categories WHERE user = 1)
GROUP BY u.user;

字符串
产出:
| 用户|CNT|
| --|--|
| 2 | 8 |
| 3 | 6 |
| 4 | 6 |
| 5 | 10 |
或者你可以:

SELECT u.user, COUNT(DISTINCT animal) AS cnt
FROM (SELECT DISTINCT user FROM user_categories WHERE user <> 1) AS u
JOIN user_categories uc ON uc.user IN (1, u.user)
GROUP BY u.user;


您可能可以将这两个查询中的DISTINCT user子查询替换为users表,但您没有包含详细信息。
这里有一个db<>fiddle

相关问题