0

我在以下查询中收到此错误

SELECT 
CASE WHEN recipient = 5 THEN sender ELSE recipient END AS F_ID,u.username 
FROM friendships f LEFT JOIN users u ON F_ID=u.id 
WHERE 5 IN (f.recipient, f.sender)

两列recipientsender都存在。为什么我不能在 on 子句中使用 F_ID?

4

4 回答 4

2

因为F_ID不是列名。这只是一个别名。ON 子句只使用列名。或者,您可以使用此查询:

SELECT F_ID, u.username FROM (
    SELECT 
    CASE WHEN recipient = 5 THEN sender ELSE recipient END AS F_ID, sender, recipient
    FROM friendships f
)tmp
LEFT JOIN users u ON F_ID=u.id 
WHERE 5 IN (tmp.recipient, tmp.sender)
于 2013-10-29T09:16:29.437 回答
2

一种方法是使用子查询。另一种方法是使 JOIN 条件更复杂:

LEFT JOIN users ON u.id = IF(f.recipient = 5, f.sender, f.recipient)
于 2013-10-29T09:20:25.193 回答
1

我没有表结构来测试我的代码,但是当你不能使用别名时,你必须不用它们:

SELECT 
CASE WHEN recipient = 5 THEN sender ELSE recipient END AS F_ID, u.username 
FROM friendships f
LEFT JOIN users u ON CASE WHEN recipient = 5 THEN sender ELSE recipient END=u.id 
WHERE 5 IN (f.recipient, f.sender)
于 2013-10-29T09:22:14.450 回答
0

LEFT如果不需要,也许您可​​以通过这种方式修改查询:

SELECT 
CASE WHEN recipient = 5 THEN sender ELSE recipient END AS F_ID,u.username 
FROM friendships f, users u 
WHERE (recipient = 5 AND sender = u.id) OR (recipient != 5 AND recipient = u.id)
于 2013-10-29T09:20:28.960 回答