[英]SELECT with LEFT JOIN returns NULL values
I've two tables: 我有两个桌子:
posts : 帖子 :
id | id_author | content | year
1 | 1 | hello | 2015
2 | 1 | world | 2016
3 | 2 | hi | 2016
favorites : 最爱 :
id | id_author | id_post | year
1 | 3 | 2 | 2016
And I want to do a SELECT
to get the posts
data by the favorites
using LEFT JOIN
. 我想使用LEFT JOIN
进行SELECT
以按favorites
获取posts
数据。 So, I did: ( taking into account that I am logged in with the user with id_author = 3) 因此,我做到了:(考虑到我是使用id_author = 3的用户登录的)
SELECT p.id, p.id_author, p.content, p.year, f.id_post
FROM favorites f
LEFT JOIN posts p
ON f.id_post = p.id
WHERE f.id_author = 3
ORDER BY f.id
DESC
So, I did: ( $sql
is equal to the query above) 所以,我做了:( $sql
等于上面的查询)
if(count($sql) > 0) {
var_dump($sql);
}
But the output is: 但是输出是:
array(1) {
[0]=>
array(5) {
["id"]=>
NULL
["id_author"]=>
NULL
["content"]=>
NULL
["year"]=>
NULL
["id_post"]=>
string(1) "2"
}
}
Why is returning NULL
? 为什么返回NULL
?
Given the schema and data of the OP the following query is not syntactically valid: 给定OP的模式和数据,以下查询在语法上无效:
SELECT p.id, p.id_author, p.content, p.year, f.id_post
FROM favorites f
LEFT JOIN posts p
ON f.id_post = p.id
WHERE id_author = 3
ORDER BY f.id DESC
as there is an ambiguity concerning the field used by the predicate of the WHERE
clause: id_author = 3
. 因为WHERE
子句的谓词使用的字段存在歧义: id_author = 3
。
You most probably have p.id_author = 3
, which means the field of the right table of the LEFT JOIN
operation is used by the WHERE
clause. 您很可能具有p.id_author = 3
,这意味着WHERE
子句使用LEFT JOIN
操作的右表字段。 This turns the LEFT JOIN
into an INNER JOIN
operation, yielding no results. 这会将LEFT JOIN
变成INNER JOIN
操作,没有结果。 So, you probably have to use: 因此,您可能必须使用:
WHERE f.id_author = 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.