如果user_id在一个MySQL查询中有status=1到这product_id 2,3,4中的任何一个,我想返回1,否则返回0

Table: user_status

status_id    user_id    product_id    status
---------------------------------------------
1               27        2             1
2               27        3             0
3               27        4             1
4               32        2             1
5               35        4             1
6               40        2             0
7               40        3             1
8               41        2             0
9               41        3             1
10              45        4             0

我try 了以下查询,

SELECT status FROM `user_status` WHERE `user_id` = '27'  AND status = '1' AND product_id IN (2,9,11);

推荐答案

您可以根据需要使用EXISTS,因为它返回True(1)或False(0)

CREATE TABLE user_status
    (`status_id` int, `user_id` int, `product_id` int, `status` int)
;
    
INSERT INTO user_status
    (`status_id`, `user_id`, `product_id`, `status`)
VALUES
    (1, 27, 2, 1),
    (2, 27, 3, 0),
    (3, 27, 4, 1),
    (4, 32, 2, 1),
    (5, 35, 4, 1),
    (6, 40, 2, 0),
    (7, 40, 3, 1),
    (8, 41, 2, 0),
    (9, 41, 3, 1),
    (10, 45, 4, 0)
;
SELECT
Exists(SELECT 
    1
FROM
    `user_status`
WHERE
    `user_id` = '27' AND status = '1'
        AND product_id IN (2 , 9, 11)) answer;
1
SELECT
Exists(
SELECT 
    1
FROM
    `user_status`
WHERE
    `user_id` = '49' AND status = '1'
        AND product_id IN (2 , 9, 11)) answer
0

db<>fiddle 100

Mysql相关问答推荐

如何重新采样SQL数据库

在mySQL中使用子查询和WHERE子句的JOIN

左联接重复问题

如何在WooCommerce中更新pm_Virtual.meta_Value=#39;否

如何根据购买的商品数量查找 unique_ids 的数量

使用sql查找源和最终目的地

如何在 MySQL 中使用从 SELECT IF 返回的布尔值

连接两个表.使用连接列作为分组依据,然后根据时间戳 Select 最新行

带有 PARTITION BY 子句的 ROW_NUMBER() 停止在 MariaDB 上工作

将 wordpress 自定义字段转换为单个数组

如何显示患者预约中的专业人员姓名?

使用带有 ELSEIF 和 ELSE 的 3 列更新问题

在 MySQL 中,我应该 Select 哪种排序规则?

在 MySQL 中检测 utf8 损坏的字符

在mysql中复制没有数据的数据库 struct (带有空表)

在 MySQL 中找不到 outfile 创建的文件

在 MySQL 中签名或未签名

匹配 IN 子句中的所有值

在 PHP 中运行 MySQL *.sql 文件

将数据库从 Postgres 迁移到 MySQL