简体   繁体   中英

MySQL: subquery in LEFT JOIN

I have a problem. I want to use subquery tm in LEFT JOIN .. ON

SELECT t.*, 
    (SELECT `uid` FROM `truck_transport` tm WHERE tm.from = t.station ORDER BY RAND() LIMIT 1) as tm 
FROM `truck_trailer` t 
LEFT JOIN `truck_transport` tm2 ON (tm2.uid = tm) ...

If I use subquery in FROM result of rand is always the same.

Sorry for my language :/

try this

SELECT t.*, tm.uid
FROM `truck_trailer` t 
    LEFT JOIN (SELECT `uid` FROM `truck_transport` ORDER BY RAND() LIMIT 1) as tm 
    ON (tm.uid = t.station)

mynawaz has written a correct query.

Your subquery will always return only one result because of limit 1 . If you want only one result to come then use JOIN instead of LEFT JOIN . because left join table always returns matching rows and non matching with NULL of right side table.

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