mysql - 如果在记录中找不到,则在 mysql 中获取其他 where case

标签 mysql sql

需要检查where情况,如果没有找到where type='P'则记录type='C'

这是表格

paper_id  | product_id  | type
    1          1           P
    2          1           P
    3          1           C
    4          1           C
    5          2           C
    6          2           C

product_id12,需要获取那些有type='P'的记录但那些没有type='P'记录的产品则从记录type='C'

获取

查询后需要这个结果

paper_id  | product_id  | type
    1          1           P
    2          1           P
    5          2           C
    6          2           C

我试试

从表中选择 *,其中 CASE WHEN type !='P' THEN type='C' ELSE type='P'END

但不工作

最佳答案

select paper_id, product_id, type from your_tab
where type = 'P'
union all
select t1.paper_id, t1.product_id, t1.type from your_tab t1
where t1.type = 'C'
  and not exists (select 1 from your_tab t2 
                  where t2.product_id = t1.product_id and t2.type = 'P');

关于mysql - 如果在记录中找不到,则在 mysql 中获取其他 where case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27456997/

相关文章:

mysql - laravel5.1 按日期排序结果 (created_at)

sql - 首先编写数据库脚本与通过 SQL Server Management Studio 构建数据库然后生成脚本

sql - 使用 CTE,即使 tableA 未返回任何结果,我如何从 tableB 中选择行?

mysql - 如何正确产生对应的SQL

mysql - 大于条件下mysql性能对比

mysql - 如何创建 sql 脚本以将多列数据作为 json 迁移到单列中

mysql - 如何从一个表中选择一列并从另一个表中选择另一列

sql - CHECK 限制出生日期?

php - jQuery Ajax Post,将它们添加到数据库,返回数据并再次重复该过程

php - Mysql 父子表减少数据库调用或在 PHP 中合并