MYSQL需要group by但查询会产生错误的结果

时间:2018-01-24 09:53:00

标签: mysql

给出一个看起来像这样的表

reportID username
-----------------
1      | a
1      | b
1      | c
2      | a
3      | c
3      | a

给定一个包含2个或更多用户名的查询,它应该返回包含用户名和匹配的reportID的行。

例如,如果给出a和b,它将返回

reportID username
-----------------
1      | a
1      | b

因为他们共享一个reportID。

SELECT reportID, username 
FROM players 
WHERE username IN('a', 'b') 
group by reportID, username
having count(reportID) > 1

尽可能接近我。按用户名添加组会破坏查询并返回0结果,但如果没有,则会产生此错误:

1055 - Expression #2 of SELECT list is not in GROUP BY clause and contains 
nonaggregated column 'x.x.username' which is not functionally dependent on 
columns in GROUP BY clause; this is incompatible with 
sql_mode=only_full_group_by

我可以做些什么来完成这项工作?

2 个答案:

答案 0 :(得分:1)

尝试此查询:

SELECT reportID, username 
FROM players 
WHERE reportID in (
  select reportID
     from players where username IN('a', 'b') 
     group by reportID
     having count(reportID) > 1
)

答案 1 :(得分:0)

计算是没用的,只需这样做:

q1