这与我最近发表的一篇文章非常类似:但它有点不同。所以,如果它看起来很熟悉:请原谅我的学习曲线试图理解:“那么这个案子怎么样,那个案子怎么样......”
我有一个很好的小查询。它查询单个“客户”表
这是表: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)吉姆和(2)汤姆和回归
5 Oscar 622 First 5125551212
3 Steve 653 Pine 5125901977
答案 0 :(得分: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
答案 1 :(得分: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
,name
和address
来自任意记录。但是,因为只有一个(由于having
子句),这些将是该记录中的字段。
答案 2 :(得分: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