MYSQL选择并分组列值

时间:2013-07-19 10:39:15

标签: mysql

我有一个MYSQL表 - 为了简化它 - 三列:名称,地址和主要住所。

可能存在名称重复的行。我想制作一个返回一个人姓名和地址的select语句。如果他们在表中两次,这意味着他们有两个地址。但是,如果其中一个是“主要住所”,我希望它只返回主要住所。否则,它应该返回两个地址。 谢谢!

表:

Name | Address | Primary Residence
John Smith | 123 Main Str | Yes
John Smith | 456 June Str | 
Mike Dore  | 893 West St  |
Jake John  | 999 East St  |
Jake John  | 145 South St |

返回:

Name | Address
John Smith | 123 Main Str
Mike Dore  | 893 West St
Jake John  | 999 East St
Jake John  | 145 South St

2 个答案:

答案 0 :(得分:3)

这是一种方式......

CREATE TABLE addresses 
(Name VARCHAR(20) NOT NULL
,Address VARCHAR(20) NOT NULL
,is_primary TINYINT NULL
,PRIMARY KEY (name,address)
);

INSERT INTO addresses VALUES
('John Smith','123 Main Str',1),
('John Smith','456 June Str',NULL),
('Mike Dore','893 West St',NULL),
('Jake John','999 East St',NULL),
('Jake John','145 South St',NULL);


SELECT * FROM addresses;
+------------+--------------+------------+
| Name       | Address      | is_primary |
+------------+--------------+------------+
| Jake John  | 145 South St |       NULL |
| Jake John  | 999 East St  |       NULL |
| John Smith | 123 Main Str |          1 |
| John Smith | 456 June Str |       NULL |
| Mike Dore  | 893 West St  |       NULL |
+------------+--------------+------------+

SELECT DISTINCT x.name
              , COALESCE(y.address,x.address) address
           FROM addresses x 
           LEFT 
           JOIN addresses y 
             ON y.name = x.name 
            AND y.is_primary = 1;
+------------+--------------+
| name       | address      |
+------------+--------------+
| Jake John  | 145 South St |
| Jake John  | 999 East St  |
| John Smith | 123 Main Str |
| Mike Dore  | 893 West St  |
+------------+--------------+

答案 1 :(得分:2)

可以使用Sub Query完成。

select * from TBL where NAME not in (select NAME from TBL where residence='PRI')
union 
select * from TBL where residence='PRI';

编辑: 问题更新后:

select * from TBL where NAME not in (select NAME from TBL where residence='yes')
union 
select * from TBL where residence='yes'

http://sqlfiddle.com/#!2/39493/5/0