首页 > 解决方案 > MySQL - 根据不同的条件忽略某些行

问题描述

例如,我有一Pokemon列包含某些数据,其中许多重复

口袋妖怪

Wartotle
Pichu
Pikachu
Pichu
Kadabra
Charmelon
Squirtle
Wartotle
Wartotle
Pidgeotto
Pidgeotto
Diglett

我需要的是忽略某些数据,如果相同的特定数据column不存在。在我通过以下方式获取数据之前,列中的特定数据pokemon必须存在SELECT

我想要的是一个查询,它做这样的事情,但在多个数据上

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

我知道这有点令人困惑,但这是我正在寻找的查询

标签: mysql

解决方案


您可以首先找到那些您不想包含的(子查询)并从结果中排除那些(外部查询):

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


推荐阅读