gpt4 book ai didi

sql - Left Join、Order by、MySQL优化

转载 作者:可可西里 更新时间:2023-11-01 07:57:28 24 4
gpt4 key购买 nike

我有这样的查询:

   SELECT m...., a...., r....
FROM 0_member AS m
LEFT JOIN 0_area AS a ON a.user_id = (SELECT user_id
FROM `0_area`
WHERE user_id = m.id
ORDER BY sec_id ASC LIMIT 1)
LEFT JOIN 0_rank as r ON a.rank_id = r.id
WHERE m.login_userid = '$username'

想法是从 0_area 表中获取第一行,因此尝试进行内部连接。但是,它没有按预期工作。

在 0_area 和 0_member 之间,0_member.id = 0_area.user_id。但是,有多行 0_area.user_id,我想要具有最低 sec_id 值的行。

有什么帮助吗?

最佳答案

   SELECT m...., a...., r....
FROM 0_member AS m
LEFT JOIN (SELECT user_id, min(sec_id) minsec
FROM `0_area`
GROUP BY user_id) g1 on g1.user_id=m.id
LEFT JOIN 0_area AS a ON a.user_id = g1.user_id and a.sec_id=minsec
LEFT JOIN 0_rank as r ON a.rank_id = r.id
WHERE m.login_userid = '$username'

关于sql - Left Join、Order by、MySQL优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5071550/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com