【问题标题】:select particular data from table1 which is not in table2 with where clause使用 where 子句从 table1 中选择不在 table2 中的特定数据
【发布时间】:2014-10-02 19:58:15
【问题描述】:

我想从 table1 中选择不在 table2 中的数据,但我必须从 table1 中选择特定数据

我的数据表

CREATE TABLE IF NOT EXISTS `table3` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `acc_id` int(11) NOT NULL DEFAULT '0',
  `did` int(11) NOT NULL,

  PRIMARY KEY (`id`)
) 



CREATE TABLE IF NOT EXISTS `table2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `acc_id` int(11) NOT NULL,
  `table1_id` int(11) NOT NULL,
  `did` int(11) NOT NULL,

  PRIMARY KEY (`id`)
) 


CREATE TABLE IF NOT EXISTS `table1` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `acc_id` int(11) NOT NULL DEFAULT '0',

  `name` varchar(50) DEFAULT NULL,
 PRIMARY KEY (`id`)

)

我想做

select name,id from table1 where id !=(select table1_id from table2 join table3 on table2.acc_id=table3.acc_id where table2.did=4759505 and table2.acc_id=2)and table1.acc_id=2

如果子查询返回 1 行,则上面的查询可以正常工作,但如果子查询返回多行则不行

谢谢

【问题讨论】:

    标签: mysql sql database fetch


    【解决方案1】:

    您只需将!= 更改为not in

    select name, id
    from table1
    where id not in (select table1_id
                     from table2 join
                          table3
                          on table2.acc_id = table3.acc_id
                          where table2.did = 4759505 and table2.acc_id = 2
                    ) and
          table1.acc_id = 2;
    

    注意:您还应该确保子查询中的table1_id 绝不是NULLNOT IN 在这种情况下可能不直观。通常,我更喜欢NOT EXISTS

    select name, id
    from table1
    where not exists (select table1_id
                      from table2 join
                           table3
                           on table2.acc_id = table3.acc_id
                           where table2.did = 4759505 and table2.acc_id = 2 and
                                 table1_id = table1.id
                     ) and
          table1.acc_id = 2;
    

    这会更直观地处理NULL 值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      相关资源
      最近更新 更多