我想从两个表中获取数据。从第一个表中,我需要所有名称,这些名称不是已登录用户的名称,但是已登录用户的名称必须在这两列之一中。我想使用该结果从第二张表中获取第一张表中给出的每个名称的照片名称。
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工作正常,但是当我尝试将其与INNER JOIN一起使用时,完全没有结果。我的代码:
$username = 'john';
$sql = "SELECT IF( name1 = '$username', name2, name1 ) AS otheruser
FROM names
WHERE name1 = '$username' OR name2 = '$username'";
上面的代码可以正常工作。现在,我正在尝试使用INNER JOIN添加另一个查询表。显然,代码的INNER JOIN部分没有得到 otheruser 结果,因此输出为 “无结果” 。
我的尝试如下:
$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";}
答案 0 :(得分:0)
您不能在where条件中使用别名(SQL解析器在select
之后评估where condition
,因此它不知道您使用的选择别名),您应该重复代码< / p>
"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'";
答案 1 :(得分:0)
在这些情况下,我经常喜欢使用COALESCE
函数,但是两者都起作用。
尝试这些命令并检查this fiddle。
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);