-4

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

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

桌子:

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
4

2 回答 2

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  |
+------------+--------------+
于 2013-07-19T11:05:22.010 回答
2

它可以通过子查询来完成。

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

于 2013-07-19T10:49:00.287 回答