MySQL: subquery in LEFT JOIN

时间:2015-09-14 15:33:30

标签: mysql

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 :/

2 个答案:

答案 0 :(得分:0)

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)

答案 1 :(得分:0)

mynawaz写了一个正确的查询。

由于limit 1,您的子查询将始终只返回一个结果。如果您只想要一个结果,请使用JOIN代替LEFT JOIN。因为左连接表总是返回匹配的行,与右侧表的NULL不匹配。