-1

我有一个如下的 MySQL 表:

+--------------------------------------------+
|  ID  |  State   |  Name   |     City       |
+--------------------------------------------+
|  PA1 |  PA      |  Foo    |    Philly      |
|  VA1 |  PA      |  Foo    |    Philly      |
|  DC1 |  VA      |  Foobar |  Washington    |
|  ME2 |  ME      |  Barfoo |   Portland     |
+--------------------------------------------+

现在,我想做一个 SELECT 语句,我只选择那些行 where State = SUBSTR(ID, 1, 2)除非Name只有一次出现在表中。换句话说,我想最终得到下表:

+--------------------------------------------+
|  ID  |  State   |  Name   |     City       |
+--------------------------------------------+
|  PA1 |  PA      |  Foo    |    Philly      |
|  DC1 |  VA      |  Foobar |  Washington    |
|  ME2 |  ME      |  Barfoo |   Portland     |
+--------------------------------------------+

在第二行中,State 不等于 ID 的子字符串,并且“Name”(在本例中为“Foo”)多次出现在表中,因此我们没有得到该行。但是,我也想要第三行,即使 State 再次不等于 ID 的子字符串,因为“名称”在原始表中只出现一次。

关于我可以使用什么查询来实现这一点的任何想法?我已经玩了很长时间没有成功。谢谢!

4

2 回答 2

3

EXISTS您可以在WHERE子句中使用以下内容:

select *
from yourtable t1
where state = SUBSTR(ID, 1, 2)
  or exists (select count(Name) CountName, Name
              from yourtable t2
              where t1.name = t2.name
              group by Name
              having count(name) = 1)

请参阅带有演示的 SQL Fiddle

返回结果:

|  ID | STATE |   NAME |       CITY |
-------------------------------------
| PA1 |    PA |    Foo |     Philly |
| DC1 |    VA | Foobar | Washington |
| ME2 |    ME | Barfoo |   Portland |
于 2013-01-30T15:22:44.997 回答
2
select *
from   myTable
where  State = SUBSTR(ID, 1, 2) or
       Name in (select Name from myTable group by Name having count(*)=1)
于 2013-01-30T15:18:10.277 回答