0

我有这个工作 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'

为什么?我究竟做错了什么?

4

2 回答 2

2

block是一个ALIAS,你应该使用列的名称来代替

SELECT...
FROM...
WHERE (c.id_title = :idt) AND (bl.id_user IS NULL)

之所以没有找到是因为操作顺序如下:

  • FROM 子句
  • WHERE 子句
  • GROUP BY 子句
  • HAVING 子句
  • 选择子句
  • ORDER BY 子句

如果要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

但我更喜欢第一个解决方案而不是使用子查询

于 2012-12-31T02:16:34.413 回答
2

您不能引用列别名;改为引用 true 列:

WHERE (c.id_title = :idt) AND (bl.id_user IS NULL)
于 2012-12-31T02:16:56.150 回答