简体   繁体   中英

Left Join, Order by, MySQL Optimization

I have a query like this:

   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'

The idea is to get the first row from 0_area table and hence the attempted inner join. However, it is not working as expected.

Between 0_area and 0_member, 0_member.id = 0_area.user_id. However, there are multiple rows of 0_area.user_id and I want the row having the lowest value of sec_id.

Any help please?

   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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM