简体   繁体   English

查询表中具有不同值的ID

[英]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.

相关问题 表不同于 Editor Power Query 到 Python - table distinct from Editor Power Query to Python 将 `null` 视为表唯一约束中的不同值 - Treating `null` as a distinct value in a table unique constraint 在 pypyodbc 中,如何查询表的不同值、截断旧表和 append 将不同值保存到空表 - In pypyodbc, How to query a table for its distinct values, truncate old table and append the distinct values to the empty table 将计数的行值扩展为单独的行,在 python 中添加不同的 ID - Expand counted row value into separate rows, adding distinct ID in python 如何获取应用 azure 表存储查询的不同值? - How to get distinct values applying an azure table storage query? 需要来自 Django 查询的对象 ID,其中客户 ID 是不同的 - DB mysql - need id's of objects from Django query where customer id's are distinct - DB mysql 如何在odoo中使用ORM方法从表中获得不同的价值 - How to get distinct value from table using ORM methods in odoo Django将具有唯一外键ID的所有值相加,并用相关表中的字段压缩它们 - Django Sum all values with a distinct ForeignKey ID & zip them with fields from related table django查询具有不同的ForeignKey - django query with distinct ForeignKey 子表中许多值的空用户 ID - Empty user id for many value in child table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM