MySQL PDO子查询构造帮助 - 以前从未这样做过

时间:2016-12-01 10:00:49

标签: mysql

我正在尝试在MySQL中运行子查询,但是我似乎无法让它工作。试图找到一个问题的许多帖子。这一切都在我脑海里。我希望这对你们来说很简单。

SELECT * FROM jobs x 
         LEFT JOIN status b on x.id = b.job_id 
         LEFT JOIN delivery d on x.id = d.job_id 
         LEFT JOIN logos h on x.id = h.job_id 
         LEFT JOIN customers c on x.customer_id = c.customer_id
         LEFT JOIN (SELECT * 
                    FROM communicator t 
                    WHERE x.id = t.job_id 
                    GROUP BY t.id 
                    DESC 
                    LIMIT 1)
WHERE x.status=1

所以问题是我开始子查询的最后一个LEFT JOIN。我不能让它工作。我究竟做错了什么?我只想从通信器表中添加最后一条记录的结果,因此按DESC限制1的顺序。

1 个答案:

答案 0 :(得分:0)

您混淆了2种常用的子查询类型。在针对子查询进行连接时,您需要为子查询提供别名。进一步对子查询进行连接时,你不会引用该子查询中另一个表的字段 - 而是在ON子句中引用这样的表。

我希望这样的东西: -

SELECT * 
FROM jobs x 
LEFT JOIN status b on x.id = b.job_id 
LEFT JOIN delivery d on x.id = d.job_id 
LEFT JOIN logos h on x.id = h.job_id 
LEFT JOIN customers c on x.customer_id = c.customer_id
LEFT JOIN 
(
    SELECT * 
    FROM communicator t 
    GROUP BY t.id 
) sub0
ON x.id = sub0.job_id
WHERE x.status=1

然而,另一个问题是您的子查询正在执行GROUP BY t.id,但您将返回job_id和其他字段。返回哪个特定的job_id是针对未定义的id。您的多个字段如何相关以及您需要哪些我不知道,但我怀疑您想要的是这样的事情,以获取job_id的最新id字段

SELECT * 
FROM jobs x 
LEFT JOIN status b on x.id = b.job_id 
LEFT JOIN delivery d on x.id = d.job_id 
LEFT JOIN logos h on x.id = h.job_id 
LEFT JOIN customers c on x.customer_id = c.customer_id
LEFT JOIN 
(
    SELECT job_id, MAX(id) AS id
    FROM communicator  
    GROUP BY job_id
) sub0
ON x.id = sub0.job_id
WHERE x.status=1