我在以下查询中收到此错误
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)
两列recipient
和sender
都存在。为什么我不能在 on 子句中使用 F_ID?
因为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)
一种方法是使用子查询。另一种方法是使 JOIN 条件更复杂:
LEFT JOIN users ON u.id = IF(f.recipient = 5, f.sender, f.recipient)
我没有表结构来测试我的代码,但是当你不能使用别名时,你必须不用它们:
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)
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)