[英]Left join with empty table makes the column that is joined on null in php, but works normally in phpmyadmin
I have a users
and a userfollowers
table.我有一个
users
和一个用户userfollowers
表。 They both have a user_id
column.他们都有一个
user_id
列。
The userfollowers
table might be empty or does not have a match yet for a user in the users
table, hence why i use a left join
. userfollowers
表可能是空的,或者还没有users
表中的用户匹配,因此我使用left join
。
This is my query:这是我的查询:
SELECT *
FROM users
LEFT JOIN userfollowers ON users.user_id = userfollowers.user_id
WHERE user_name = ?"
When I try to execute this query in my php prepared statement, it returns all columns correctly, except the user_id
from the users
table is suddenly NULL.当我尝试在我的 php 准备语句中执行此查询时,它会正确返回所有列,除了
users
表中的user_id
突然变为 NULL。
When I try this query in phpmyadmin, it returns all columns including the user_id
from the users
table as intended.当我在 phpmyadmin 中尝试此查询时,它会按预期从
users
表中返回包括user_id
在内的所有列。
Can someone tell me what is going on?有人可以告诉我发生了什么吗?
In PHP only 1 indice can exist in an array so the latter column, userfollowers.user_id
overwrites the first value users.user_id
.在 PHP 中,数组中只能存在 1 个索引,因此后一列
userfollowers.user_id
覆盖第一个值users.user_id
。 You need to list the columns, use aliases for all columns, or use numeric indices (which will be difficult to determine which value is which).您需要列出列,为所有列使用别名,或使用数字索引(这将很难确定哪个值是哪个)。
You could do something like this if all columns from users
should be returned:如果应返回
users
的所有列,您可以执行以下操作:
SELECT u.*, uf.somecolumn
FROM users as u
LEFT JOIN userfollowers as uf using(user_id)
WHERE user_name = ?
The as u
is a table alias, that allows you to use the shorter syntax when referencing the table. as u
是表别名,允许您在引用表时使用较短的语法。 Tha same can be done for columns.对列也可以这样做。 With original query if you needed both
user_id
s could do:如果您需要两个
user_id
,则使用原始查询可以执行以下操作:
SELECT u.user_id as users_id, uf.user_id as userfollowers_userid
FROM users as u
LEFT JOIN userfollowers as uf using(user_id)
WHERE user_name = ?
then PHP would have both $row['userfollowers_userid']
and $row['users_id']
available.那么 PHP 将有
$row['userfollowers_userid']
和$row['users_id']
可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.