Subselecting array in mysql

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Subselecting array in mysql



I have the following tables:



chatUsers


chatId | userId |
---------|---------------|
1 | 1 |
1 | 2 |
2 | 1 |
2 | 3 |



chatRooms


chatId |lastMessageTime|
---------|---------------|
1 | yesterday | //for example 1000000000
2 | today | //for example 1532473344



Let's say I am userId 1


userId 1



I would like to load all the chatRooms that I am in.



Ordered by chatRooms.lastMessageTime + I'd like to know what users are in the same chat room (chatUsers.userId)


chatRooms.lastMessageTime


chatUsers.userId



So for example in this case:


[{
"chatId": 2,
"users": [1, 3]
},
{
"chatId": 1,
"users": [1, 2]
}]



Is it possible? I've managed to make it without the users selection:


$qry = $db->prepare('SELECT cr.chatId FROM chatRooms AS cr INNER JOIN chatUsers AS cu ON cu.chatId = cr.chatId WHERE cu.userId = :userId
ORDER BY cr.lastMessageTime DESC, cr.chatId DESC');
$qry->bindParam(':userId', $userId, PDO::PARAM_INT);
$qry->execute();

$chatRooms = $qry->fetchAll(PDO::FETCH_ASSOC);



But I am unable to make a subselect inside the select..





No nested results in MySQL, or any SQL that I know of.
– Uueerdo
yesterday




1 Answer
1


$qry = $db->prepare('SELECT cr.chatId, GROUP_CONCAT(cu.userId) AS users FROM chatRooms AS cr INNER JOIN chatUsers AS cu ON cu.chatId = cr.chatId WHERE cu.userId = :userId ORDER BY cr.lastMessageTime DESC, cr.chatId DESC GROUP BY chatId');
$qry->bindParam(':userId', $userId, PDO::PARAM_INT);
$qry->execute();

$chatRooms = $qry->fetchAll(PDO::FETCH_ASSOC);



In this way you'll get users in a comma-separated string.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

pfrkoCc
o0EGJY1L yC4R wy,jMm,r1qBnRN0IDPP5SncLo,WMmiMVA7Ct6NOeZl1puucKbyd9lhyO3UkalSp6Tvy4Ip8G,WnidUpX4ttXbAyO

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

415 Unsupported Media Type while sending json file over REST Template