在我开始编写 Python 脚本之前,我想看看单独的 MySQL 是否可以产生结果。

我有一个产品 list :

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)
  • 运行 2 个循环并在所需列匹配时更新所需表。

  • 只是想看看是否存在仅 MySQL 的解决方案。

    ps:这只是一个样本,实际问题只有100个产品和1000个公司。我通过在 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
    

    最佳答案

    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
    

    关于python - 棘手的 MySQL 查询而不是 Python 脚本来实现结果?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7069837/

    10-14 19:54
    查看更多