从具有多对多关系的表中选择记录时,我遇到了一般性问题 假设我有两个表如下:
MainTable:
id <-- Primary key
description
DataTable:
id <-- Primary key
data1
data2
data3
description FOREIGN KEY of Table(MainTable)
我目前有以下查询:
myelements = executeSQL(按说明从MainTable顺序中选择不同的描述)
然后我使用从此查询中获取的元素来执行另一个查询:
for item in myelements:
executeSQL(select data1 from DataTable where description = item)
有没有办法删除这个for循环并有一个sql语句来执行此操作?
我想将DataTable中的所有记录捆绑在一起,以获取所有可用的描述 将它们存储在代码中。 所以我有一些东西:
map[description] = every row of that description in DataTable
答案 0 :(得分:1)
尝试使用join
,如下所示:
SELECT MT.description, group_concat(DT.data1)
FROM DataTable DT JOIN MainTable MT ON (DT.description = MT.description)
GROUP BY MT.description
ORDER BY MT.description