mysql来自select if in inner join的结果

jutyujz0  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(362)

我想从两个表中获取数据。从第一个表中,我需要的所有名称不是登录用户的名称,但登录用户的名称必须在这两列中的一列中。我想用这个结果从第二个表中得到第一个表中给出的每个名称的照片的名称。

table 1 names
+++++++++++++++++++++++++
id | name1   | name2    |
+++++++++++++++++++++++++
1  | john    | lea      |<- i need lea because john is in one of those two columns
-------------------------
2  | peter   | john     |<- i need peter because john is in one of those two columns
-------------------------
3  | mark    | paola    |<- no john here so query should ignore
__________________________

table 2 users
+++++++++++++++++++++++++
id | name    | photo    |
+++++++++++++++++++++++++
1  | lea     | la.jpg   |<- I want to use lea given with SELECT IF to get name of photo
-------------------------
2  | peter   | pt.jpg   |<- I want to use peter given with SELECT IF to get name of photo
-------------------------
2  | mark    | mk.jpg   |<- no match from SELECT IF so query should ignore
-------------------------

我的select if或concat工作得很好,但是当我尝试将其与内部连接一起使用时,根本没有结果。我的代码:

$username = 'john';
$sql = "SELECT IF( name1 = '$username', name2, name1 ) AS otheruser
FROM names
WHERE name1 = '$username' OR name2 = '$username'";

上面的代码工作正常。现在我尝试在查询中添加另一个具有内部联接的表。很明显,代码的内部连接部分并没有得到其他用户的结果,所以输出是“无结果”。
我的尝试是这样的:

$sql = "SELECT IF(names.name1 = '$username', names.name2, names.name1) AS otheruser, users.photo
FROM names
INNER JOIN users ON users.name = 'otheruser'
WHERE names.name1 = '$username' OR names.name2 = '$username'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {

while($row = $result->fetch_assoc()) {
$names = $row['otheruser'];
$photos = $row['photo'];
}
} else {echo "no results";}
laximzn5

laximzn51#

不能在where条件中使用别名(sql解析器计算 select 之后 where condition 所以它不知道您使用的select别名)您应该重复代码

"SELECT IF(names.name1 = '$username', names.name2, names.name1) AS otheruser, users.photo
  FROM names
  INNER JOIN users ON users.name = IF(names.name1 = '$username', names.name2, names.name1)
  WHERE names.name1 = '$username' OR names.name2 = '$username'";
ovfsdjhp

ovfsdjhp2#

我经常喜欢这个 COALESCE 在这些情况下起作用,但两者都起作用。
试试这些命令,检查一下这把小提琴。

SELECT IF (name1 = 'john', name2, name1) FROM names WHERE name1 = 'john' or name2='john';

SELECT COALESCE (IF (name1 = 'john', null, name1), IF (name2 = 'john', null, name2)) FROM names WHERE 'john' IN (name1, name2);

SELECT u.username as otheruser, u.photo FROM users u
INNER JOIN names n 
    ON u.username = COALESCE(IF (name1 = 'john', null, name1), IF (name2 = 'john', null, name2))
WHERE 'john' IN (n.name1, n.name2);

相关问题