如何从连接中的子查询访问父列

How to access parent column from a subquery within a join

我正在尝试根据用户 ID 左加入第二个 table 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`

这是否解决了您的问题?您需要在内部查询中使用 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;