MySQL - 使用CASE WHEN中的列到WHERE子句

时间:2018-04-09 21:04:25

标签: mysql

我想创建一个SQL命令,它将检查记录是否存在并且:

  

1)如果存在,则等于1,

     

2)如果它不存在,它将等于NULL。

下一步 - 我想在WHERE子句中使用这个值(1或NULL)。

因此脚本应检查table_private中是否存在记录,如果是,则应按以下方式搜索:

SELECT * FROM `images` WHERE advert_id = 5795 and img_user_id = 1

如果没有,它应该搜索:

SELECT * FROM `images` WHERE advert_id = 5795 and img_user_id is NULL

这是我的sql命令:

SELECT *, CASE WHEN NOT EXISTS (SELECT * FROM `table_private` WHERE
client_id = 1 AND id = 5795) THEN NULL ELSE 1 END AS exist_value 
FROM `images` WHERE advert_id = 5795 AND img_user_id = exist_value;

但我得到了:

Nieznana kolumna 'exist_value' w where clause 为什么?这个列是存在的 - 当我删除这部分命令:AND img_user_id = exist_value时,sql正确地将此列作为resuslt返回。

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

您可以使用HAVING根据SELECT列表中的计算值进行过滤。

SELECT *, 
        CASE WHEN NOT EXISTS (
                SELECT * 
                FROM `table_private` 
                WHERE client_id = 1 AND id = 5795) 
             THEN NULL 
             ELSE 1 
        END AS exist_value 
FROM `images` WHERE advert_id = 5795
HAVING img_user_id <=> exist_value;

<=>是空安全等于运算符,它允许与NULL进行比较。

答案 1 :(得分:0)

在外部查询中获取数据,如

SELECT * FROM (
SELECT *, 
CASE WHEN NOT EXISTS (SELECT * FROM `table_private` WHERE
client_id = 1 AND id = 5795) THEN NULL ELSE 1 END AS exist_value 
FROM `images` ) xxx
WHERE advert_id = 5795 
AND img_user_id = exist_value;

答案 2 :(得分:0)

(编辑:在收集到更多信息后,删除的内容不再适用。)

要在评论中明确说明完整性的建议:

SELECT *, CASE WHEN NOT EXISTS (SELECT * FROM `table_private` WHERE
client_id = 1 AND id = 5795) THEN NULL ELSE 1 END AS exist_value 
FROM `images` 
WHERE advert_id = 5795 
AND img_user_id 
    <=> /* exist_value */ 
      CASE WHEN NOT EXISTS (SELECT * 
                            FROM `table_private` 
                            WHERE client_id = 1 AND id = 5795) 
           THEN NULL 
           ELSE 1 
      END
;