Python3脚本与同一查询的MySQL引擎没有显示相同的结果

时间:2016-09-08 19:44:28

标签: python mysql sql python-3.x

我的python3脚本没有生成与MySQL相同的结果。我的查询返回那些值在一周内发生了变化的行。

Python脚本:

query = "SELECT cw.opportunityid, cw.probability, pw.probability, cw.stage, pw.stage, cw.amount, pw.amount, " \
    "cw.closedate, pw.closedate " \
    "FROM opty_data cw " \
    "LEFT JOIN opty_data pw ON cw.opportunityid = pw.opportunityid " \
    "AND pw.Week = \"{0}\" " \
    "WHERE cw.Week = \"{1}\" " \
    "AND IF(pw.opportunityid IS NULL, TRUE, ((cw.probability <> pw.probability) OR (cw.stage <> pw.stage) " \
    "OR (cw.Amount<>pw.Amount) OR (cw.CloseDate <> pw.CloseDate)))".format(Prev_Week,Curr_Week)
cursor.execute(query)
results = dictfetchall(cursor)
print(results)

输出:

[{
        'opportunityid' : '1',
        'probability' : '50',
        'amount' : Decimal('30.35'),
        'closedate' : datetime.date(2016, 8, 22),
        'stage' : 'Proposal'
    }, {
        'opportunityid' : '2',
        'probability' : '50',
        'amount' : Decimal('115.00'),
        'closedate' : datetime.date(2016, 6, 30),
        'stage' : 'Proposal'
    }, {
        'opportunityid' : '3',
        'probability' : '50',
        'amount' : Decimal('200.00'),
        'closedate' : datetime.date(2016, 8, 29),
        'stage' : 'Proposal'
    }
]

查询:

SELECT cw.opportunityid, cw.probability, pw.probability, cw.stage, pw.stage, cw.amount, pw.amount, cw.closedate, pw.closedate FROM opty_data cw 
LEFT JOIN opty_data pw 
ON cw.opportunityid = pw.opportunityid AND pw.Week = "2016-35" WHERE cw.Week = "2016-36" 
AND IF(pw.opportunityid IS NULL, TRUE, ((cw.probability <> pw.probability) OR (cw.stage <> pw.stage) OR (cw.Amount<>pw.Amount) OR (cw.CloseDate <> pw.CloseDate)))

MySQL正确显示预期输出:

+-----------------+-------------+-------------+----------------+----------------
+------------+-------------+------------+------------+
| opportunityid   | probability | probability | stage          | stage
| amount     | amount      | closedate  | closedate  |
+-----------------+-------------+-------------+----------------+----------------
+------------+-------------+------------+------------+
| 1 | 50          | 50          | Proposal       | Proposal
|   20.35 |    30.35 | 2016-08-22 | 2016-08-22 |
| 2 | 50          | 50          | Proposal       | Proposal
|  113.00 |    115.00 | 2016-09-06 | 2016-06-30 |
| 3 | 0           | 50          | Drop           | Proposal
|  200.00 |   200.00 | 2016-08-29 | 2016-08-29 |

1 个答案:

答案 0 :(得分:1)

Python字典由唯一的键值对组成,因此一个键只能在字典中出现一次。由于原始SQL查询从单个行中的同一列返回两个不同的值,因此第二次出现的列将覆盖字典中的第一个。但是,您可以通过使用AS关键字为列指定别名来轻松解决此问题。请查看以下示例:

SELECT 
    p1.name AS p1name, 
    p2.name AS p2name 
FROM 
    p1, p2 
WHERE 
    p1.id != p2.id