【问题标题】:Find values missing in a column from a set (mysql)从集合中查找列中缺少的值(mysql)
【发布时间】:2016-05-13 04:44:40
【问题描述】:

我正在使用 mysql。

我有一个有列 id 的表。

假设我有一组 id 输入。我想知道表中缺少哪些所有 id。

如果集合为“ida”、“idb”、“idc”且表中只包含“idb”,则返回值应为“ida”、“idc”。

这可以通过单个 sql 查询实现吗?如果没有,执行此操作的最有效方法是什么。

请注意,我不允许使用存储过程。

【问题讨论】:

  • 您可以在应用程序代码中轻松完成此操作。你用的是什么编程语言?
  • 听起来像WHERE id NOT IN( 'ida', 'idb', 'idc')
  • 类似SELECT a.id FROM input_set a LEFT JOIN table b ON a.id=b.id WHERE b.id IS NULL
  • @tadman,是的,应用程序代码通常是执行此操作的更可取的方式。有时我会使用.sql 文件为方便起见,因此在某些用例中您根本不会使用任何应用程序。 :-)

标签: mysql sql


【解决方案1】:

MySQL 只会返回存在的行。要返回丢失的行,您必须有两个表。

第一个表可以是临时的(特定于会话/连接),以便多个实例可以同时运行。

create temporary table tmpMustExist (text id);
insert into tmpMustExist select "ida";
insert into tmpMustExist select "idb";
-- etc

select a.id from tmpMustExist as a
  left join table b on b.id=a.id
  where b.id is null; -- returns results from a table that are missing from b table.

这可以通过单个 sql 查询实现吗?

嗯,是的。让我按照自己的方式进行操作,首先使用 union all 组合 select 语句。

create temporary table tmpMustExist (text id);
insert into tmpMustExist select "ida" union all select "idb" union all select "etc...";
select a.id from tmpMustExist as a left join table as b on b.id=a.id where b.id is null;

请注意,我使用 union all,它比 union 快一点,因为它跳过了重复数据删除。

您可以使用create table...select。我经常这样做并且非常喜欢它。 (这也是复制表的好方法,但会删除索引。)

create temporary table tmpMustExist as select "ida" union all select "idb" union all select "etc...";
select a.id from tmpMustExist as a left join table as b on b.id=a.id where b.id is null;

最后,您可以使用所谓的“派生”表将整个内容整合到一个单一的、可移植的 select 语句中。

select a.id from (select "ida" union all select "idb" union all select "etc...") as a left join table as b on b.id=a.id where b.id is null;

注意:as 关键字是可选的,但阐明了我对 ab 所做的事情。我只是创建要在joinselect 字段列表中使用的短名称

【讨论】:

    【解决方案2】:

    有个窍门。您可以创建一个包含预期值的表,也可以为每个值使用多个选择的并集。

    然后您需要找到标准具中的所有值,而不是测试表中的值。

    CREATE TABLE IF NOT EXISTS `single` (
      `id` varchar(10) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    INSERT INTO `single` (`id`) VALUES
    ('idb');
    
    SELECT a.id FROM (
       SELECT 'ida' as id
       UNION
       SELECT 'idb' as id
       UNION
       SELECT 'idc' AS id
    ) a WHERE a.id NOT IN (SELECT id FROM single)
    

    【讨论】:

      【解决方案3】:
      //you can pass each set string to query
      //pro-grammatically you can put quoted string
      //columns must be utf8 collation
      
      select * from
      (SELECT 'ida' as col 
      union  
      SELECT 'idb' as col 
      union  
      SELECT 'idc' as col ) as setresult where col not in (SELECT value FROM `tbl`)
      

      【讨论】:

        猜你喜欢
        • 2019-04-15
        • 1970-01-01
        • 2020-02-17
        • 1970-01-01
        • 2020-03-18
        • 1970-01-01
        • 2021-04-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多