1

这与我最近发表的一篇文章非常相似:但有点不同。因此,如果它看起来很熟悉:请原谅我试图理解的学习曲线:“那么这个案例和那个案例呢......”

我有一个很好的小查询。它查询单个“客户”表

这是表格:SQLFiddle 在这里:http ://sqlfiddle.com/#!2/1fcea

CREATE  TABLE `clients` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(45) NULL ,
  `address` VARCHAR(45) NULL ,
  `state` VARCHAR(45) NULL ,
  `foo` VARCHAR(45) NULL ,
  `phone` VARCHAR(45) NULL ,
  PRIMARY KEY (`id`) );

INSERT INTO`clients` 
   (`name`, `address`, `state`, `foo`, `phone`) 
 VALUES 
   ('Jim', '123 Main', 'MO', '876', '2038221661');
INSERT INTO`clients` 
   (`name`, `address`, `state`, `foo`, `phone`) 
 VALUES 
   ('Tom ', '234 Elm', 'MO', '433', '2038221661');
INSERT INTO`clients` 
   (`name`, `address`, `state`, `foo`, `phone`) 
 VALUES 
   ('Steve', '653 Pine', 'CT', '863', '5125901977');
INSERT INTO`clients` 
   (`name`, `address`, `state`, `foo`, `phone`) 
 VALUES 
   ('Dave', '654 Oak', 'NV', '872', '8769085435');
INSERT INTO`clients` 
   (`name`, `address`, `state`, `foo`, `phone`) 
 VALUES 
   ('Oscar', '622 FIrst ', 'LA', '625', '5125551212');

这是查询

SELECT id, 
       name, 
       address, 
       phone 
FROM   clients 
WHERE  state IN ( 'MO', 'LA', 'CT' ) 
       AND foo > 40 
ORDER  BY foo 

它返回:

2   Tom     234 Elm     2038221661
5   Oscar   622 First   5125551212
3   Steve   653 Pine    5125901977
1   Jim     123 Main    2038221661

我想完全抑制任何没有完全唯一电话号码的记录。

我需要它压制 (1) Jim 和 (2) Tom and Return

5   Oscar   622 First   5125551212
3   Steve   653 Pine    5125901977
4

3 回答 3

3
SELECT id, 
       name, 
       address, 
       phone 
FROM   clients 
WHERE  state IN ( 'MO', 'LA', 'CT' ) 
       AND foo > 40 
       AND phone not in 
       (
          select phone 
          from clients 
          group by phone
          having count(*) > 1
       )
ORDER  BY foo 
于 2013-07-18T00:05:57.713 回答
2

您实际上可以使用以下命令执行此操作group by

SELECT id, name, address, phone 
FROM   clients 
WHERE  state IN ( 'MO', 'LA', 'CT' ) AND foo > 40 
group by phone
having count(*) = 1
ORDER  BY foo;

这按电话号码分组。、id和来自任意记录nameaddress但是,因为只有一个(由于该having子句),这些将是该记录中的字段。

于 2013-07-18T02:18:47.253 回答
1

这应该排除重复的数字:

SELECT id, 
   name, 
   address, 
   phone 
FROM   clients 
WHERE  state IN ( 'MO', 'LA', 'CT' ) 
   AND foo > 40 
   AND phone not in (select phone from clients 
                    group by phone having count(*) > 1)
ORDER  BY foo 
于 2013-07-18T00:09:06.683 回答