简体   繁体   中英

GROUP_CONCAT for grouping multiple rows for a user

How do I create a query for grouping the users who have sent or received message from user 1.

SQL: http://sqlfiddle.com/#!9/7d6a9 for usr_msg
http://sqlfiddle.com/#!9/3ac0f for token_msg.

I have 2 tables: token_msgs and user_msgs :

我的桌子的图片:

I want to show the list of user ids (non repeting, like the user 2, 3 and 4 should be visible only once but in DESC order) who has sent/received message from user1 [from_id=1 OR to_id=1]. I am not able to create the logic for GROUP_CONCAT and not sure if i really need to join these 2 tables.

在此处输入图片说明

Thank you.

Assuming you have a list of users, you can use IN or EXISTS :

select u.*
from users u
where u.id in (select from_id from user_msgs where to_id = 1) or
      u.id in (select to_id from user_msgs where from_id = 1) or
      u.id in (select from_id from token_msgs where to_id = 1) or
      u.id in (select to_id from token_msgs where from_id = 1);

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