MySQL从多个表中选择

时间:2022-07-21 01:59:17

I have some code (inherited) which selects a row from table 'members' and also some details from a row from table 'image':

我有一些代码(继承)从表'members'中选择一行,并从表'image'的行中选择一些细节:

SELECT members.main,members.id,image.main,image.thumb,bio,
altered,members.title,author 
FROM members,image WHERE members.main = image.id

This works fine in all cases, except those where the field 'members.main' is empty. Is there a way to keep the same functionality of this code (i.e. match up the member with the image) while catering for cases where 'members.main' is empty?

这在所有情况下都可以正常工作,除了字段'members.main'为空的那些情况。有没有办法保持这段代码的相同功能(即将成员与图像匹配),同时迎合'members.main'为空的情况?

I tried

我试过了

WHERE members.main = image.id OR members.main = ''

but this returned garbled results.

但这会导致结果出现乱码。

Thanks,

谢谢,

G

G

1 个解决方案

#1


3  

Use a left outer join:

使用左外连接:

SELECT
    members.main,
    members.id,
    image.main,
    image.thumb,
    bio,
    altered,
    members.title,
    author
FROM members
LEFT JOIN image
ON members.main = image.id

A LEFT JOIN returns all rows from the left table (members) whether or not they match a row in the right table (image).

LEFT JOIN返回左表(成员)中的所有行,无论它们是否与右表(图像)中的行匹配。

#1


3  

Use a left outer join:

使用左外连接:

SELECT
    members.main,
    members.id,
    image.main,
    image.thumb,
    bio,
    altered,
    members.title,
    author
FROM members
LEFT JOIN image
ON members.main = image.id

A LEFT JOIN returns all rows from the left table (members) whether or not they match a row in the right table (image).

LEFT JOIN返回左表(成员)中的所有行,无论它们是否与右表(图像)中的行匹配。