不知道如何通过两个表的mySQL查询来实现这一点

不知道如何通过两个表的mySQL查询来实现这一点,mysql,sql,Mysql,Sql,我有两个表users和distance。在一个页面中,我需要通过一个简单的查询列出所有用户,例如select*from users,其中active=1 order by id desc 有时,我需要从distance表中输出数据,并将users中的用户ID字段与distance表中的两列匹配,例如userID\u 1和userID\u 2。此外,在距离表中,上述两列中的任何一列也必须与where子句中指定的id($userID)匹配 这是我想到的最好的: select a.*,

我有两个表
users
distance
。在一个页面中,我需要通过一个简单的查询列出所有用户,例如
select*from users,其中active=1 order by id desc

有时,我需要从
distance
表中输出数据,并将
users
中的用户ID字段与
distance
表中的两列匹配,例如
userID\u 1
userID\u 2
。此外,在距离表中,上述两列中的任何一列也必须与where子句中指定的id(
$userID
)匹配

这是我想到的最好的:

select 
    a.*,
    b.distance 
from 
    users a,
    distance b 
where 
    ((b.userID_1='$userID' and a.id=b.userID_2) 
  or (a.id=b.userID_1 and b.userID_2='$userID')) 
 and a.active=1 
order by a.id desc
此查询的唯一问题是,如果
distance
表中没有where子句的条目来查找匹配项,则查询根本不会返回任何内容。我仍然希望它从
user
表返回该行,如果没有匹配项,则将
distance
返回为null

对于这种情况,我无法确定是否需要使用联接、联合、子查询或其他任何方法

谢谢。

试试这个:

select a.*, b.distance 
from users a 
left join distance b on (a.id=b.userID_1 or a.id=b.userID_2) and 
                        (b.userID_1 = '$userID' or b.userID_2 = '$userID') 
where a.active=1 
order by a.id desc 
试试这个:

select a.*, b.distance 
from users a 
left join distance b on (a.id=b.userID_1 or a.id=b.userID_2) and 
                        (b.userID_1 = '$userID' or b.userID_2 = '$userID') 
where a.active=1 
order by a.id desc 
使用左连接

select 
    a.*,
    b.distance 
from 
    users a
    left join distance b on
       (b.userID_1=? and a.id=b.userID_2) 
    or (b.userID_2=? and a.id=b.userID_1)
where 
    a.active=1 
order by a.id desc
并使用事先准备好的声明。将文本替换到查询中容易受到SQL注入攻击。

使用左连接

select 
    a.*,
    b.distance 
from 
    users a
    left join distance b on
       (b.userID_1=? and a.id=b.userID_2) 
    or (b.userID_2=? and a.id=b.userID_1)
where 
    a.active=1 
order by a.id desc

并使用事先准备好的声明。将文本替换到查询中容易受到SQL注入攻击。

您需要在“用户”和“距离”之间使用左连接。因此(并非有意双关语),您将始终从“用户”表中获取行以及从“距离”中获取任何匹配行(如果有)

我注意到您使用的是SQL-89连接语法(“隐式连接”),而不是SQL-92连接语法(“显式连接”)。这是我写的

我建议您将查询改为

select a.*, b.distance 
from users a left join distance b 
on ((b.userID_1='$userID' and a.id=b.userID_2) 
or (a.id=b.userID_1 and b.userID_2='$userID')) 
where a.active=1 
order by a.id desc

“用户”和“距离”之间需要左连接。因此(并非有意双关语),您将始终从“用户”表中获取行以及从“距离”中获取任何匹配行(如果有)

我注意到您使用的是SQL-89连接语法(“隐式连接”),而不是SQL-92连接语法(“显式连接”)。这是我写的

我建议您将查询改为

select a.*, b.distance 
from users a left join distance b 
on ((b.userID_1='$userID' and a.id=b.userID_2) 
or (a.id=b.userID_1 and b.userID_2='$userID')) 
where a.active=1 
order by a.id desc