为什么这个查询不起作用?

时间:2014-03-19 11:27:58

标签: mysql sql select left-join

以下是有问题的查询:

SELECT e.id, e.name, u.x_account_username, ao.id
FROM x_evidence e
LEFT JOIN x_ambition_owner ao 
ON e.ambition_id = ao.id
LEFT JOIN x_user u
ON ao.profile_id = u.id
WHERE e.updated BETWEEN '2014-03-19 10:16:00' AND '2014-03-19 11:16:00' 

谁能看到我做错了什么?

证据表:

id       ambition_id      name     updated
1jk      2ef              abc      2014-03-19 10:33:31

野心主人表:

id       ambition_id        profile_id
1op      2ef                1abc

用户表:

id      x_account_username
1abc    rex hamilton

我希望我的回归得到:

所述时间之间的证据ID,姓名,用户名,相关野心ID(但这些可能会有所不同)

由于

1 个答案:

答案 0 :(得分:3)

一种不起作用的方式是where子句将第一个left join转变为inner join。因此,您不会从查询中获取所需的所有行。事实上,你可能没有得到任何一个。

您可以通过将条件移动到on子句来解决此问题:

SELECT ao.id AS a_id, e.id AS e_id, e.name AS evidence_name,
       u.x_account_username AS username, 'evidence_edit' AS type
FROM x_ambition_owner ao
LEFT JOIN x_evidence e 
     ON ao.id = e.ambition_id
     AND e.updated BETWEEN '2014-03-19 10:16:00' AND '2014-03-19 11:16:00'
LEFT JOIN x_user u
     ON ao.profile_id = u.id;
编辑(OP):

这是我将要使用的查询:

SELECT e.id, e.name, u.x_account_username AS username, a.ambition_id
FROM x_evidence e
LEFT JOIN x_ambition_owner a
ON e.ambition_id = a.ambition_id
LEFT JOIN x_user u
ON a.profile_id = u.id
WHERE e.updated BETWEEN '2014-03-19 10:00:00' AND '2014-03-19 11:16:00'