为什么这个查询在SQLite中不起作用,但在MySQL和MSAccess中工作正常?

时间:2014-03-19 23:27:21

标签: mysql sql sqlite

我有一个非常复杂的SQL查询,如in this fiddle

所示
SELECT payer_payment.payer_id, 
       Sum(payer_payment.amount)                             AS total_paid, 
       Sum(payer_payment.pays * payments_share.single_share) AS fair_share 
FROM   payers 
       INNER JOIN (payer_payment 
                   INNER JOIN (SELECT payment_id, 
                                      Sum(amount) / Sum(pays) AS single_share 
                               FROM   payer_payment 
                               GROUP  BY payment_id) AS payments_share 
                           ON payer_payment.payment_id = 
                              payments_share.payment_id) 
               ON payers.id = payer_payment.payer_id 
WHERE  payers.user_id  = 1 
GROUP  BY payer_payment.payer_id; 

在小提琴中,它可以在MySQL上正常运行,但是当我在SQLite数据库上运行它时,它会引发错误,引用:

  

(1没有这样的栏目:payer_payment.payer_id)

当列清楚存在时。

或简单地返回0结果,具体取决于SQLite实现(WebSQL vs SQLite.js)

这是什么原因,是否可以使我的查询更加数据库不可知?

1 个答案:

答案 0 :(得分:1)

在SQLite中,您可以使用INTEGER PRIMARY KEY获取自动增量列。 (如果你依赖查询中payers.id的实际值,你应该明确地给它们。)

在不需要时,不应尝试嵌套连接:

SELECT payer_payment.payer_id,
       Sum(payer_payment.amount)                             AS total_paid,
       Sum(payer_payment.pays * payments_share.single_share) AS fair_share
FROM       payers
INNER JOIN payer_payment
        ON payers.id = payer_payment.payer_id
INNER JOIN (SELECT payment_id,
                   Sum(amount) / Sum(pays) AS single_share
            FROM   payer_payment
            GROUP  BY payment_id) AS payments_share
        ON payer_payment.payment_id = payments_share.payment_id
WHERE payers.user_id = 1
GROUP BY payer_payment.payer_id;

SQLFiddle