![](/img/trans.png)
[英]How to join 2 tables and get the latest records from other table in one-to-many relation using SqlAlchemy ORM
[英]How to get distinct values from many columns of table using sqlAlchemy ORM?
我创建了一个包含这些表的数据库
Employee(id, name, deptid, salary)
Department(id, name)
其中包含这些值
Employee
id | name | deptid | salary. |
------- ------------ ------------ -----------
1 Alex 1 600000
2 Larry 1 700000
3 Jesse 3 400000
4 Alex 2 500000
5 Marcus 3 400000
Department
id | name |
-------- -----------
1. Engineering
2. Finance
3. Sales
我想从数据库的每一列中获取不同的值我希望 output 看起来像这样
name
------
Alex
Larry
Jesse
Marcus
deptid
-------
1
3
2
我写了一个 ORM 这样的查询
session.query(Employee.name, Employee.deptid).distinct().all()
这让我回来
[('Alex',1,), ('Larry',1), ('Jesse', 3),('Alex',2),('Marcus',3)]
这是返回两个列组合的不同值,这不是我正在寻找的所需解决方案,而是我正在寻找,而是我希望在一个查询本身中具有不同列的不同值的解决方案。
SELECT DISTINCT
应用于正在选择的完整行。
因此,您将需要两个SELECT DISTINCT
查询来查找两个不同列中的不同值。
session.query(Employee.name).distinct().all()
session.query(Employee.deptid).distinct().all()
您还应该直接使用Department.id
来查找其不同的值,而不是使用外键Employee.deptid
,除非您只想查找引用的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.