[英]Query table for id of distinct value
I have a table with multiple values that repeat sometimes. 我有一个表,有时会重复多个值。 ex(1,'test', 2, 'test, 3, 'somevalue', 4, 'somevalue' etc)
ex(1,'test',2,'test,3,'somevalue',4,'somevalue'等)
So basically what I am trying to do is query the table for all the distinct values along with their ids. 因此,基本上我想做的就是在表中查询所有不同的值及其ID。 I'm new to
sqlalchemy
and can't seem to figure out how. 我是
sqlalchemy
新手,似乎无法弄清楚该怎么做。
This is what I have now: 这就是我现在所拥有的:
reportTypes = DBSession.query(TDeviceType.sDeviceType).distinct()
where sDeviceType is my string value and ixDeviceType is my id. 其中sDeviceType是我的字符串值,ixDeviceType是我的ID。 This query however only returns the distinct value.
但是,此查询仅返回不同的值。 Any suggestions?
有什么建议么? I could do a loop for each value and get the id however that just seems like a bad idea
我可以为每个值做一个循环并获取ID,但这似乎是一个坏主意
equivalent of what I want to do: 相当于我想做的事:
select distinct(sDeviceType), ixDeviceType FROM TDeviceType
YIf I understand the question correctly, you want a list of ids for each value. 如果我正确理解了这个问题,则需要每个值的ID列表。 While there might be a way to do this in pure SQLAlchemy, it seems simple enough to do this in Python.
尽管在纯SQLAlchemy中可能有一种方法可以执行此操作,但在Python中似乎很简单。
reportTypes = {}
for id, value in DBSession.query(TDeviceType.ixDeviceType, TDeviceType.sDeviceType):
reportTypes.setdefault(value, []).append(id)
print reportTypes # looks like {'test': [1, 2], 'somevalue': [3, 4]}
Each key is a distinct sDeviceType
and each value is a list of ixDeviceType
. 每个键是不同的
sDeviceType
,每个值是ixDeviceType
的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.