简体   繁体   English

mysql连接成对相关的3张表

[英]mysql join 3 tables related in pairs

► Context : I work in a museum (for real), people come everyday, they buy tickets for themselves (humans) and sometimes they also buy tickets for drinks and foods (objects). ►上下文 :我在博物馆里工作(真实),人们每天都来,他们自己(人类)购买门票,有时他们也购买饮料和食物(物品)门票。 There are events, tickets have the same names per event but the prices are different. 有活动,每个活动的门票名称相同 ,但价格不同。

► The problem : I have to create a report with 2 results : total sales (visitors + food + drinks) and how many people came (visitors only) for a specific event. ►问题 :我必须创建一个包含2个结果的报告:特定事件的总销售额 (游客+食物+饮料)和有多少人 (仅限游客)。 Next is an image of the 3 tables in the database, how they relate and some sample data : 接下来是数据库中3个表的图像,它们之间的关系以及一些示例数据:

  • Table TICKETS relates to SALES_MAIN through EVENT_ID column. 表TICKETS通过EVENT_ID列与SALES_MAIN 相关
  • Table SALES_MAIN relates to SALES_DETAIL through IDMAIN_ID columns. 表SALES_MAIN通过IDMAIN_ID列与SALES_DETAIL相关。
  • Table SALES_DETAIL have a column TICKET_NAME but it's not unique in table TICKETS. 表SALES_DETAIL的列为TICKET_NAME,但在表TICKETS中不是唯一的。

在此处输入图片说明

► The question : How to get both results, total sales and human count , for event 555 in one "select" ? ►问题 :如何在一次“选择”中获得事件555的结果, 总销售额和人数 I tried next 2 "select" but when I combine them with another INNER JOIN I get cartesian results : 我尝试了下2个“选择”,但是当我将它们与另一个INNER JOIN结合使用时,会得到笛卡尔结果:

Get detail sales for event 555 : 获取事件555的详细销售:

SELECT sales_detail.* FROM sales_main
INNER JOIN sales_detail ON sales_detail.main_id = sales_main.id
WHERE sales_main.event_id = '555'

Get tickets for event 555 : 获取事件555的门票:

SELECT * FROM tickets WHERE tickets.event_id = '555'

Use: 采用:

SELECT 
  SUM(CASE WHEN sd.ticket_name IN ('adult', 'child') THEN sd.quantity 
           ELSE 0 END) AS total_visitors,
  SUM(sd.quantity * t.price)  AS total_sales
FROM sales_main sm
JOIN sales_detail sd
  ON sd.main_id = sm.id
JOIN ticket t
  ON t.event_id = sm.event_id
 AND t.ticket_name = sd.ticket_name
WHERE sm.event_id = '555';

Conditional aggregation could also be based on type: 条件聚合也可以基于以下类型:

SUM(CASE WHEN t.ticket_type ='human' THEN sd.quantity ELSE 0 END)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM