简体   繁体   中英

MySQL: select multiple rows which has specific field value

I'm having a users_conversations table contains a conversation_id and a user_id to tell which users are in the same conversation. I want to find any conversation_id which has user_id 76 and user_id 146 (which are ids 28, 31 and 32. These ids are not unknown to me. I just have both users ids) I tried

select * from users_conversations where user_id = 146 or user_id = 76 GROUP BY conversation_id

but I get

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

How can I do that?

在此处输入图像描述

select * from users_conversations
where conversations_id in (select conversations_id from user_conversations where user_id=76) 
AND conversations_id in (select conversations_id from user_conversations where user_id=146)

You can filter the table for these users, group by conversation_id and set the condition in the having clause:

select conversation_id
from users_conversations
where user_id in (76, 146)
group by conversation_id
having count(distinct user_id) = 2

You may omit distinct if there is no case of duplicate users for each conversation_id .

Did you mean instead:

select * from users_conversations where user_id = 146 or user_id = 76

Why do you want to use group?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM