我遇到了下面解释的问题:
id | user_id | admin
1 | 1 | 2
2 | 1 | 5
3 | 2 | 5
4 | 2 | 5
5 | 3 | 5
6 | 4 | 5
我需要编写一个查询,以便让与WHERE
条AND
中传递的管理员ID相关联的所有用户拥有多个交易(可以与另一个管理员。)
If user_id is 5 then result should come
user_id
1
2
尝试了
SELECT
user_id ,
COUNT(*) count
FROM
table
WHERE admin = 5
GROUP BY
user_id
Having
count > 1
但是上面提到的这个查询会跳过只有一个admin = 5的事务的user_id,另一行又有另一个admin。
建议?
答案 0 :(得分:2)
汇总user_id
并断言:
5
),
SELECT user_id
FROM yourTable
GROUP BY user_id
HAVING SUM(CASE WHEN admin = 5 THEN 1 ELSE 0 END) > 0 AND
COUNT(*) > 1;
答案 1 :(得分:0)
试试这个
SELECT user_id from `tablename` WHERE admin IN( SELECT admin FROM `tablename` GROUP BY admin HAVING count(*) > 1)
答案 2 :(得分:0)
在admin=5
上的查询过滤器中,并且对这些用户具有单独的子查询,这些用户具有多于1个事务。您需要在子查询中计数,因为admin=5
条件不适用于计数。
SELECT DISTINCT user_id
FROM yourTable
WHERE admin_id=5
AND user_id IN (SELECT user_id FROM yourTable GROUP BY user_id HAVING COUNT(*)>1)
答案 3 :(得分:0)
SELECT user_id 从test_table1 GROUP BY user_id 具有和(例如,当管理员=&n;那么1 0结束时)> 0 和 COUNT(user_id)> 1;
答案 4 :(得分:0)
如果我理解你的问题,你想问:
这将为您提供每个用户的列表(仅限用户ID)
SELECT DISTINCT table.user_id
FROM table
JOIN (
SELECT user_id
,COUNT(DISTINCT admin_id) num_admins
FROM table
GROUP BY user_id
HAVING COUNT(DISTINCT admin_id) > 1
) multi_admin
ON table.user_id = multi_admin.user_id
WHERE admin = 5 -- if you want to look only at user_ids somehow associated with