直接用MySQL查询代替Python脚本实现结果?
在我开始写Python脚本之前,我想先看看单靠MySQL能不能得到想要的结果。
我有一份产品清单:
PID Product
-----------
1 AAA
2 ABC
3 BAC
4 CAB
5 CBA
我还有一份公司订单的清单,这些公司多次订购这些产品:
CID PID
-------
1 1
2 3
1 5
3 2
1 1
2 3
我想要的结果是:
CID AAA ABC BAC CAB CAB CBA
---------------------------
1 Y Y
2 Y
3 Y
如果我用Python来做,我会怎么做呢?
- 创建一个临时表,里面有这些列(CID AAA ABC BAC CAB CAB CBA)
- 运行两个循环,当需要的列匹配时更新目标表。
我只是好奇,看看有没有单靠MySQL就能解决的问题。
补充一下:这只是一个示例,实际问题中有几百个产品和几千家公司。我是通过在Excel中转置数据,创建了一个包含100个产品的临时表,然后把它转成了MySQL表。
以下是我最终采用的方法。谢谢大家的反馈。
########### Python script to generate the MySQL query ##############
#MySQL Connection String Goes here#
#Generate MySQL 'CASE' logic
cursor = db.cursor()
if __name__ == '__main__':
cursor.execute("select PID, Product from products")
productlist = cursor.fetchall()
for product in productlist:
print ("max(case when PID = %s then 'Y' else '' end) as `%s`,") % (product[0], product[1])
db.close()
使用nick建议的格式生成查询。
select cid,
max(case when pid = 1 then 'Y' else '' end) as AAA,
max(case when pid = 2 then 'Y' else '' end) as ABC,
max(case when pid = 3 then 'Y' else '' end) as BAC,
max(case when pid = 4 then 'Y' else '' end) as CAB,
max(case when pid = 5 then 'Y' else '' end) as CBA
from companies
group by cid
5 个回答
0
为什么会有重复的数据呢?比如有两次出现的1 1和2 3。
我不太明白为什么要这样表示数据。如果是为了在你的界面上显示,这样做其实不好。我建议你还是用Python来处理,简单来说可以这样做:
1) 创建一个表
2) 获取数据
3) 对于从选择的结果集中每一条结果,比如cid和pid,给表标记为'Y'
2
3
select cid,
max(case when pid = 1 then 'Y' else '' end) as AAA,
max(case when pid = 2 then 'Y' else '' end) as ABC,
max(case when pid = 3 then 'Y' else '' end) as BAC,
max(case when pid = 4 then 'Y' else '' end) as CAB,
max(case when pid = 5 then 'Y' else '' end) as CBA
from companies
group by cid
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言进行解释。