我有这个工作的MySQL查询(它被剥离以仅显示相关的行):
SELECT
c.id AS id_comment
, bl.id_user AS block
FROM comments AS c
LEFT JOIN user_blocked AS bl ON
(c.id_user = bl.id_user AND :uid = bl.id_user_blocked)
OR (c.id_user = bl.id_user_blocked AND :uid = bl.id_user)
WHERE (c.id_title = :idt)
有效!但我只是希望得到block IS NULL
的结果,所以我在WHERE
中添加了一个新条件:
SELECT
c.id AS id_comment
, bl.id_user AS block
FROM comments AS c
LEFT JOIN user_blocked AS bl ON
(c.id_user = bl.id_user AND :uid = bl.id_user_blocked)
OR (c.id_user = bl.id_user_blocked AND :uid = bl.id_user)
WHERE (c.id_title = :idt) AND (block IS NULL)
但是我收到了这个错误:
SQL ERROR: SQLSTATE[42S22]: Column not found: 1054
Unknown column 'block' in 'where clause'
为什么呢?我做错了什么?
答案 0 :(得分:2)
block
是ALIAS
,您应该使用该列的名称
SELECT...
FROM...
WHERE (c.id_title = :idt) AND (bl.id_user IS NULL)
找不到它的原因是因为操作顺序如下:
如果您希望使用block
而不是列名,则需要将整个查询放在SubQuery
中。例如
SELECT *
FROM
(
SELECT c.id AS id_comment,
bl.id_user AS block
FROM comments AS c
LEFT JOIN user_blocked AS bl
ON (c.id_user = bl.id_user AND :uid = bl.id_user_blocked) OR
(c.id_user = bl.id_user_blocked AND :uid = bl.id_user)
WHERE c.id_title = :idt
) s
WHERE block IS NULL
但我更喜欢第一种解决方案,而不是使用子查询。
答案 1 :(得分:2)
您无法引用列别名;改为引用真列:
WHERE (c.id_title = :idt) AND (bl.id_user IS NULL)