【发布时间】:2018-03-15 04:48:56
【问题描述】:
我有 3 张桌子:
用户 - 带有 id、client_id 和用户名
maindata - 带有 client_id、用户名和描述(每个 client_id 有许多用户名)以及我需要计数的主要数据。
clients - 带有 client_id 和 client_name(不是用户名)
我需要从具有以下字段的 maindata 中获取数据:
usernames, client_id, and description
查看 maindata 中的所有记录:有多少记录具有相同的用户名、client_id 和描述。
获得计数后,我需要从 maindata 中获取与该用户名关联的 user_id。
我觉得我可以在一个 SQL 调用中做到这一点,但现在我在获取所有用户的列表后运行一个 for 循环(因为它具有用户名和 client_id),但不确定我是否需要,我可能能够将这些包含在我的查询中。
cur.execute("SELECT * FROM users")
users = cur.fetchall()
for u in users:
user = u[2]
client_id = u[1]
cur.execute("SELECT clients.name,maindata.client_id,maindata.username,users.id,COUNT(*) "
"FROM maindata CROSS JOIN users "
"INNER JOIN clients ON maindata.client_id=clients.id "
"WHERE description LIKE '%teal%' "
"AND maindata.username='{}' AND maindata.client_id='{}' ".format(user,client_id)) #This will return the client and the number of countableDatas
totalCountswithIDs = cur.fetchall()
所以最终结果应该是返回值:
- 客户端名称(在客户端中找到)
- 客户端 ID(在 maindata 中找到)
- 用户名(在主数据中找到)
- 用户 ID(在用户中找到)
- 计数(针对客户 ID + 用户名 + 指定描述的所有组合)
我离得很远吗?提前感谢您的帮助!
样本数据:
maindata:
id, client_id, username, description
(1, '1', 'rusty', 'blue'),
(2, '2', 'john', 'yellow brick road'),
(3, '3', 'helen', 'teal'),
(4, '3', 'helen', 'teal'),
(5, '3', 'helen', 'teal'),
users:
id, client_id, username
(1743, 2, 'john'),
(1742, 3, 'helen'),
(1189, 1, 'rusty'),
clients:
id, name
(1, 'Apple'),
(2, 'Amazon'),
(3, 'Google'),
这样的结果是:
- 苹果,1,生锈,1189,1
- 亚马逊,2,约翰,1743,1
- 谷歌,3,海伦,1742,3
最后一个有 3 个,因为有 3 个匹配我对“teal”的 LIKE 搜索,例如。
【问题讨论】:
-
没有样本数据和预期的输出,不清楚你想要实现什么。
-
我刚刚附加了示例数据
-
试试这个演示rextester.com/ZWIC63437