作为示例,我有一个 Pokemon
列,其中包含某些数据,其中许多是重复的
Sprite 宝可梦
Wartotle
Pichu
Pikachu
Pichu
Kadabra
Charmelon
Squirtle
Wartotle
Wartotle
Pidgeotto
Pidgeotto
Diglett
如果同一列上的特定数据不存在,我需要忽略某些数据。在我通过 SELECT
pokemon
列中的特定数据必须存在
我想要的是一个对多个数据执行类似操作的查询
SELECT * FROM table
(
If `Pichu` doesn't exists then don't `SELECT` `Pikachu`
If `Abra` doesn't exists then don't `SELECT` `Kadabra`
If `Squirtle` doesn't exists then don't `SELECT` `Wartotle`
If `Pidgety` doesn't exists then don't `SELECT` `Pidgeotto`
If `Squirtle` doesn't exists then don't `SELECT` `Wartotle`
If `Charmander` doesn't exists then don't `SELECT` `Charmeleon`
)
所以我需要的 SELECT
查询的最终结果将导致这样的结果
Wartotle
Pichu
Pikachu
Pichu
Squirtle
Wartotle
Wartotle
Diglett
我知道这是一个有点令人困惑的请求,但这是我正在寻找的查询
最佳答案
您可以首先找到那些您不想包含的内容(子查询)并从结果中排除那些内容(外部查询):
select t.name
from table1 t
where t.name not in (
select s.skip
from (
select 'Pichu' as search, 'Pikachu' as 'skip'
union
select 'Abra', 'Kadabra'
union
select 'Squirtle', 'Wartotle'
union
select 'Pidgety', 'Pidgeotto'
union
select 'Squirtle', 'Wartotle'
union
select 'Charmander', 'Charmeleon'
) as s
left join table1 t1 on t1.name=s.search
where t1.name is null
);
顺便说一句,根据您的规则,Charmelon
应包含在结果集中。
参见dbfiddle
关于MySQL - 根据不同条件忽略某些行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59907704/