左边排除MySQL中的JOIN

时间:2012-12-31 02:14:28

标签: mysql sql join

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

为什么呢?我做错了什么?

2 个答案:

答案 0 :(得分:2)

blockALIAS,您应该使用该列的名称

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

找不到它的原因是因为操作顺序如下:

  • FROM clause
  • WHERE子句
  • GROUP BY子句
  • HAVING条款
  • SELECT条款
  • 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

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

答案 1 :(得分:2)

您无法引用列别名;改为引用真列:

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