我目前在弄清楚如何通过一个字段将同一组中存在于该组中的不同对象转换为同一字段但值不同的另一组时遇到麻烦。我正在使用sqlalchemy将烧瓶连接到Postgresql我有这样的ReferenceCity模型:
class ReferenceCity(Base):
__tablename__ = 'reference_cities'
id = Column(Integer, primary_key=True)
site_id = Column(Integer, ForeignKey('sites.id'), nullable=False)
name = Column(String)
基本上,ReferenceCity将按site_id进行2组分组。示例site_id = 1和site_id = 2
名称字段可以重复,例如:可以有2个带有name
字段的ReferenceCity对象都是Newyork,但每个对象都有不同的site_id
。
SELECT count(*)
FROM public.reference_cities
WHERE site_id=1;
//got 711
SELECT count(*)
FROM public.reference_cities
WHERE site_id=2;
//got 709
[我在pgadmin上执行了count(*)命令,以检查每个site_id组中的对象数,并且我从site_id = 1中获得了711个对象,从site_id = 2中获得了709个对象。
所以必须有2个其他组别没有的城市,而我正试图找到一个SELECT查询来查找那些缺少的2个城市,而我找不到任何城市。
示例数据:
ReferenceCity table
id name site_id
1 newyork 1
2 california 1
3 texas 1
4 newyork 2
5 california 2
6 texas 2
7 detroit 2
8 chicago 2
我如何选择从site_id = 2获取底特律和芝加哥很高兴有人可以提供帮助:)
您可以使用EXCEPT
子句来隔离多余的行:
SELECT name
FROM reference_cities
WHERE site_id = 2
EXCEPT
SELECT name
FROM reference_cities
WHERE site_id = 1;
输出:
postgres=# create table reference_cities (id int, name text, site_id int);
CREATE TABLE
postgres=# insert into reference_cities values (1,'newyork',1),(2,'california',1),(3,'texas',1),(4,'newyork',2),(5,'california',2),(6,'texas',2),(7,'detroit',2),(8,'chicago',2);
INSERT 0 8
postgres=# SELECT name
FROM reference_cities
WHERE site_id = 2
EXCEPT
SELECT name
FROM reference_cities
WHERE site_id = 1;
name
---------
chicago
detroit
(2 rows)