IF、CASE、WHEN 语句根据 SQL 中的特定值返回 table 的不同行

IF, CASE, WHEN Statements Returning different rows of a table depending on a certain value in SQL

我想编写一个 SQL 查询,其中 returns 是 table 的一部分(不是 returns 新的 table)。

If, Case 或任何语句应决定返回哪些行。

该语句应查看特定 ID 的列 'comments'(类型 VARCHAR)中的特定值,可以是 'new' 或 'played'。

如果 'comments' 是 LIKE '%new%' 那么查询应该 select ID 1、2 和 3,否则如果 'comments' 是 LIKE '%played%'那么查询应该 select ID 4.

我无法得到这个 运行 因为我只找到在 table 中改变值的例子,而不是 selecting 行。

希望有人能帮助我:)


解释问题的新方法

如果 ID = 2 的行中 comments 列的值为 'new',则查询应该 select ID 为 1、2 和 3 的行。

输入table:

ID   title   comments
---------------------
1    title1  sth
2    title2  *new*
3    title3    
4    title4  sth

预期输出:

ID   title   comments
---------------------
1    title1  sth
2    title2  new
3    title3    

否则,如果 ID = 2 的行中 comments 列的值为 'played',则查询应该 select ID 为 4 的行。

输入table(注意ID 2中'comments'的值变了)

ID   title   comments
---------------------
1    title1  sth
2    title2  *played*
3    title3    
4    title4  sth

预期输出:

ID   title   comments
---------------------
4    title4  sth 

这是我认为可以完成任务但事实并非如此的代码

IF (SELECT comments FROM table WHERE ID = 2) LIKE 'new'
    SELECT ID, title, comments 
    FROM table 
    WHERE ID = 1 OR ID = 2 OR ID = 3

IF (SELECT comments FROM table WHERE ID = 2) LIKE 'played'
    SELECT ID, title, comments 
    FROM table 
    WHERE ID = 4

您是否不想使用流程控制程序。

您可以随时切换到动态 sql

SELECT IF ((SELECT comments FROM table_a WHERE ID = 2) LIKE 'new',
@sql := 'SELECT ID, title, comments FROM table_a WHERE ID = 1 OR ID = 2 OR ID = 3',
IF ((SELECT comments FROM table_a WHERE ID = 2) LIKE 'played', @sql :=
'SELECT ID, title, comments FROM table_a WHERE ID = 4', @sql := 'SELECT SLEEP(0)'));

  PREPARE Stnt FROM @sql;
  EXECUTE Stnt;
  DEALLOCATE PREPARE Stnt;

只需 JOIN 表格:

SELECT t1.ID, t1.title, t1.comments 
FROM table1 t1
  JOIN table1 t2
    ON ((t1.ID = 1 OR t1.ID = 2 OR t1.ID = 3) AND t2.comments LIKE 'new') OR
       (t1.ID = 4 AND t2.comments LIKE 'played')
WHERE t2.ID = 2;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=593d8e703006322f9a77df60e9985b1f