我是SQL的新手,我想在一个看似简单的问题中寻求帮助,但在我看来这很麻烦。
我有下表:
ID NAME CITY
---------------------
1 John new york
2 Sam new york
3 Tom boston
4 Bob boston
5 Jan chicago
6 Ted san francisco
7 Kat boston
我想要一个查询,以返回居住在数据库中注册的另一个人也居住的城市中的所有人员。
对于我上面显示的表格,答案是:
ID NAME CITY
---------------------
1 John new york
2 Sam new york
3 Tom boston
4 Bob boston
7 Kat boston
答案 0 :(得分:3)
我会使用EXISTS
:
SELECT t.*
FROM table t
WHERE EXISTS (SELECT 1 FROM table t1 WHERE t1.city = t.city AND t1.name <> t.name);
答案 1 :(得分:2)
这实际上是一个两部分的问题:
我们分两个部分来回答。让我们也做一个简化的假设(您的问题中没有提到),即“用户”表在每个城市的每个用户只有一个条目。
要查找具有多个用户的城市:
using PropertyChanged;
using System.ComponentModel;
namespace WpfApp1.ViewModels
{
/// <summary>
/// A base model that fires Property Changed events as needed
/// </summary>
[AddINotifyPropertyChangedInterface]
public class ViewModelBase : INotifyPropertyChanged
{
/// <summary>
/// The event is fired when any child property changes its value
/// </summary>
public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { };
}
}
现在,让我们找到这些城市的所有用户:
SELECT City FROM Users GROUP BY City HAVING COUNT(*) > 1
答案 2 :(得分:1)
这将为您提供同一城市超过1次的行:
SELECT persons.*
FROM persons
WHERE (SELECT COUNT(*) FROM persons AS p GROUP BY CITY HAVING p.CITY = persons.CITY) > 1
答案 3 :(得分:1)
为避免相关的子查询导致嵌套循环,可以执行自联接:
SELECT id, name, city
FROM persons
JOIN (SELECT city
FROM persons
GROUP BY city HAVING count(*) > 1) AS cities
USING (city);
这可能是性能最高的解决方案。
答案 4 :(得分:0)
This can be expressed many ways. Here is one possible way:
select * from persons p
where exists (
select 1 from persons p2
where p2.city = p.city and p2.name <> p.name
)
答案 5 :(得分:0)
这只是与已发布的其他口味不同。
SELECT ID,
name,
city
FROM (SELECT DISTINCT
ID,
name,
city,
COUNT(1) OVER (PARTITION BY city) AS cityCount
FROM table) t
WHERE cityCount > 1