嵌套选择为参数的位置

时间:2018-03-18 23:07:43

标签: sql nested aggregate

我有以下表结构:

预订

id  
booking_id  
price  

门票

id  
booking_id  
amount

付款

SELECT * FROM tickets
  WHERE
  sum of all payment amounts with this booking_id
  >=
  sum of all ticket prices with this booking_id

我想选择所有已全额付款的门票。

主查询的伪SQL:

SELECT sum(payment.amount) FROM payments WHERE payments.booking_id = XXX

SQL表示“使用此booking_id的所有付款金额的总和”:

SELECT sum(tickets.price) FROM tickets WHERE tickets.booking_id = XXX

用于“使用此booking_id的所有票价总和”的SQL:

 db.execSQL("INSERT INTO " +tableprod+" (id_prod, name) VALUES (7791234567898, 'chocolate')");

如何将第二个和第三个查询集成到第一个查询中以返回所有付费彩票?

1 个答案:

答案 0 :(得分:0)

这是另一个,加入符合您标准的记录的嵌套查询:

SELECT tickets.* 
FROM 
tickets 
INNER JOIN
(
    (
        SELECT tickets.booking_id, sum(tickets.price) as owed 
        FROM tickets
        GROUP BY tickets.booking_id
    ) AS a 
    INNER JOIN
    (
        SELECT payments.booking_id, sum(payments.amount) as paid
        FROM payments
        GROUP BY payments.booking_id
    ) AS b
    ON a.booking_id = b.booking_id AND a.owed <= b.paid
)
ON tickets.booking_id = a.booking_id