我正在尝试根据用户的ID继续加入第二个表格useri_ban
,并附加条件:useri_ban.start_ban = max_start
。
为了让我计算max_start
,我必须运行以下子查询:
(SELECT MAX(ub.start_ban) AS max_start, user_id FROM useri_ban ub WHERE ub.user_id = useri.id)
此外,为了将max_start
添加到每一行,我需要将此子查询的结果内部连接到主结果中。但是,似乎一旦我应用了该连接,子查询就无法再访问useri.id
。
我做错了什么?
SELECT
useri.id as id,
useri.email as email,
useri_ban.warning_type_id as warning_type_id,
useri_ban.type as type,
useri.created_at AS created_at
FROM `useri`
inner join
(SELECT MAX(ub.start_ban) AS max_start, user_id FROM useri_ban ub WHERE ub.user_id = useri.id) `temp`
on `useri`.`id` = `temp`.`user_id`
left join `useri_ban` on `useri_ban`.`user_id` = `useri`.`id` and `useri_ban`.`start_ban` = `max_start`
答案 0 :(得分:0)
这可以解决您的问题吗?您需要在内部查询中使用GROUP BY而不是另一个连接。
SELECT useri.id, useri.email, maxQuery.maxStartBan
FROM useri
INNER JOIN
(
SELECT useri_ban.user_id ubid, MAX(useri_ban.startban) maxStartBan
FROM useri_ban
GROUP BY useri_ban.user_id
) AS maxQuery
ON maxQuery.ubid = useri.id;