[英]Php mysql left join no result issue
i've a query using left join, my problem is if right table is empty i cant get value which i'm using for ON clause, i mean; 我有使用左联接的查询,我的问题是,如果右表为空,我无法获取我用于ON子句的值;我的意思是;
SELECT members.*,
photos.*
FROM members LEFT JOIN photos on members.member_id = photos.member_id
now, if it returns a result from photos table, its ok. 现在,如果它从photos表返回结果,就可以了。 But when there is no result from photos table, it returns from members table but it does not returns member_id.
但是,当photos表没有结果时,它从members表返回,但不返回member_id。 it returns all others from members table but not member_id
它从成员表返回所有其他成员,但不返回member_id
The problem here is that you have two columns with the same name. 这里的问题是您有两个具有相同名称的列。
Try renaming one to avoid the collision: 尝试重命名以避免冲突:
SELECT *, members.member_id AS real_member_id
Give the members.member_id
an alias name. 给
members.member_id
一个别名。
SELECT members.member_id as m_id, [other column you want]
FROM members LEFT JOIN photos on members.member_id = photos.member_id
What do you mean by it returns all others from members table but not member_id
? 您是什么意思,
it returns all others from members table but not member_id
? Is it returning (null)
? 返回
(null)
吗? Basically yes it all returns all the records from the members table because you are joining it from the left ( members table). 基本上是的,因为您是从左侧( 成员表)将其联接,所以所有这些都将返回成员表中的所有记录。 But if the record from
member_id
does not exist, the it returns null
. 但是,如果
member_id
中的记录不存在,则返回null
。 You have to give an ALIAS
for that column since you have two fields with the same name. 您必须为该列提供一个
ALIAS
,因为您有两个名称相同的字段。
members.member_id AS MemberID
It's better to expicitedly write which columns you want in the SELECT
list: 最好在
SELECT
列表中写出所需的列:
SELECT members.member_id
members.name,
photos.photo_id,
photos.filename,
...
Then you can be sure that no 2 columns have the same name. 然后,您可以确保没有2列具有相同的名称。 It's also better because when one of the table's structure is changed, your query will break and you'll find out easily why.
更好的做法是,当更改表的结构之一时,查询将中断,并且您将容易找到原因。 Now it was broken by working in an unexpected way.
现在,它以一种意外的方式被打破了。
If the only common column is member_id
and you really need all the columns, this will work too: 如果唯一的公共列是
member_id
并且您确实需要所有列,那么这也将起作用:
SELECT *
FROM members NATURAL LEFT JOIN photos
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.