我正在制作一个事件应用程序,该程序可让人们一起创建具有名称,数量和价格的事件和票证类型,当用户购买票证时,所购买的交易会插入到不同的表格中,购买交易中包含{ {1}},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
但是这对于大型数据库是不利的……无论情况如何,这都是有害的。
有人知道更好的出路吗?
我也尝试过使用JOIN但被卡住了
select id
, eventfk
, name
, qty (select count(*) from ticketsalestable) available
, price
from tickettypetable
答案 0 :(得分:1)
我认为您希望加入票务合计的集合,例如
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
编辑 票证也是加入条件
答案 1 :(得分:0)
基于Turo's
的答案,我对其进行了修改,并提出了这个建议
SELECT t.id, t.name, t.quantity, IF(t.price = 0,'FREE',t.price), (t.quantity - IFNULL(s.sold, 0)) as available FROM tickettypetb t LEFT JOIN (select sl.eventfk, sl.tickettypefk, COUNT(sl.eventfk) as sold from salestb sl GROUP BY sl.tickettypefk ORDER BY sl.tickettypefk DESC) s ON s.tickettypefk = t.id AND s.eventfk = t.eventfk WHERE t.eventfk = 22 GROUP BY t.id ORDER BY t.id DESC