[英]How to LEFT JOIN a table not keeping all the records from left table?
I have three tables:我有三张桌子:
1 - Dinners, with dinners details 1 - 晚餐,含晚餐详情
dinnerid | description | date
1234
5678
9012
2 - dinners_detgroups, with the groups that are participating to the dinners 2 - Dinners_detgroups,包含参加晚宴的组
dinnerid | groupid
1234 4897
1234 5643
5678 2398
3- groups_users, with the users that are part of groups 3- groups_users,包含属于组的用户
groupid | userid
4897 48
4897 97
5643 56
5643 43
I'm trying to make a query that returns the details of a dinner with all the groupids that are participating in which there is the userid I'm looking for我正在尝试进行查询,返回晚餐的详细信息,其中包含我正在寻找的用户 ID 参与的所有 groupid
For example: userid 48 ---> groupid 4897 ---> dinnerid 1234例如:userid 48 ---> groupid 4897 ---> Dinnerid 1234
I want that the query returns the detail of the dinner with id 1234 and the groupid that are participating (in this case 4897 5643)我希望查询返回 id 为 1234 的晚餐的详细信息和参与的 groupid(在本例中为 4897 5643)
I've tried with this我试过这个
SELECT dinners.*, array_agg(dinners_detgroups.groupid) AS groupid
FROM dinners
INNER JOIN dinners_detgroups ON dinners.dinnerid = dinners_detgroups.dinnerid
LEFT JOIN groups_users
ON dinners_detgroups.groupid = groups_users.groupid
AND groups_users.userid = ' + request.user.userid + '
GROUP BY dinners.dinnerid
But returns me all the dinners, not only the dinner in which there is user 48.但是将所有晚餐都还给我,而不仅仅是用户 48 所在的晚餐。
and with this有了这个
SELECT dinners.*, array_agg(dinners_detgroups.groupid) AS groupid
FROM dinners
INNER JOIN dinners_detgroups ON dinners.dinnerid = dinners_detgroups.dinnerid
INNER JOIN groups_users
ON dinners_detgroups.groupid = groups_users.groupid
AND groups_users.userid = ' + request.user.userid + '
GROUP BY dinners.dinnerid
That returns the right dinner but only the groupid in which is user id 48 (groupid 4897) but i want all the groupid that are participating to the dinner (in this case also groupid 5643)这会返回正确的晚餐,但只有用户 id 48(groupid 4897)的 groupid,但我想要所有参与晚餐的 groupid(在这种情况下也是 groupid 5643)
If I understand correctly, you want all groups to be included when one of them has the requested user.如果我理解正确,您希望在其中一个具有请求的用户时包含所有组。 If so, I think you can use this method:
如果是这样,我认为您可以使用此方法:
SELECT d.*, array_agg(DISTINCT dd.groupid) AS groupid
FROM dinners d INNER JOIN
dinners_detgroups dd
ON d.dinnerid = dd.dinnerid JOIN
groups_users gu
ON dd.groupid = gu.groupid
GROUP BY d.dinnerid
HAVING bool_or(gu.userid = ?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.