我正在制作一个事件应用程序,该程序可让人们一起创建具有名称,数量和价格的事件和票证类型,当用户购买票证时,所购买的交易会插入到不同的表格中,所购交易包括event ID
, ticket type ID
和其他字段。在这一点上,我想使用ticket type name
,quantity
,price
和available tickets
提取我的所有票证类型。
这是我桌子的图形外观
TicketTypeTable
---------------------------------
|id |eventfk | name | qty | price|
|--------------------------------|
TicketSalesTable
----------------------------------------------
|id |userfk |eventfk | ticketype | qty | price|
|---------------------------------------------|`
我想要的输出是
--------------------------------------------
|id |eventfk | name | qty |available | price|
|-------------------------------------------|
我可以用
inner select
这样select id
, eventfk
, name
, qty (select count(*) from ticketsalestable) available
, price
from tickettypetable
但这对于大型数据库是不利的……无论情况如何,这都是不利的。
有人知道更好的出路吗?
我也尝试过使用JOIN但被卡住了
SELECT t.id, t.eventfk, t.name, t.quantity, t.price FROM tickettypetable t LEFT JOIN ticketsalestable s ON s.eventfk = t.eventfk WHERE t.eventfk = 10
最佳答案
我想您希望加入票务合计的汇总,例如
SELECT t.id, t.eventfk, t.name, t.quantity, t.price, (t.qty - s.sold) as available FROM tickettypetable t LEFT JOIN
( select eventfk, tickettype, sum(qty) as sold from ticketsalestable group by eventfk, tickettype) s
ON s.eventfk = t.eventfk and t.id = s.tickettype
WHERE t.eventfk = 10
根据优化程序,将where条件也添加到聚合中可能更快
SELECT t.id, t.eventfk, t.name, t.quantity, t.price, (t.qty - s.sold) as available FROM tickettypetable t LEFT JOIN
( select eventfk, tickettype, sum(qty) as sold from ticketsalestable group by eventfk, tickettype where eventfk = 10) s
ON s.eventfk = t.eventfk and t.id = s.tickettype
WHERE t.eventfk = 10
编辑
票证也是加入标准