我有两个桌子。
带有events
的一列,
id, start_time, end_time, location_id
,另外一个带有orders
的列:
id, time_placed, location_id
基本上,我想要的是一个包含所有事件的新表,以及一个包含该事件的订单数的新列。我将这些订单分组的方式取决于是否将它们放置在事件的开始时间和结束时间之间,以及它们是否与事件共享相同的location_id。我对如何做到这一点感到很困惑。每个事件都有自己的唯一ID,每个订单都有自己的唯一ID。
由于表的大小,我无法真正将表导出到csv并尝试在Python中进行任何操作,因此必须在mySQL中完成。
我尝试探索CASE语句和循环,但是我尝试的任何方法都没有用,所以我可能做错了。
所以我最后想要的是一个带有变量的表: event_id和order_count。
id order_count
1 7383
2 383
3 83838
答案 0 :(得分:0)
您可以尝试使用联接并计数
select e.start_time, e.end_time, e.location_id, count(*)
from events e
inner join orders o on o.location_id = e.location_id
group by e.start_time, e.end_time, e.location_id
答案 1 :(得分:0)
select e.*, count(o.location_id) as order_count
from events e
left join orders o
on o.location_id = e.location_id
and o.time_placed >= e.start_time
and o.time_placed <= e.end_time
group by e.id
您应该在orders(location_id, time_placed)
上有一个索引。但是即使有该索引,大表的查询也可能很慢,因为MySQL引擎在优化范围上的JOIN时遇到了麻烦。该问题可能在最新版本中已解决。
注意:我假设events.id
是主键,并且您使用默认设置的MySQL。如果您在ONLY_FULL_GROUP_BY
模式下遇到麻烦,则应将events
中所有选定的列添加到GROUP BY子句中。
答案 2 :(得分:0)
您想要的是一起查看EVENTS
和ORDERS
表,从而构成一个JOIN
。但是,由于您想要所有events
,而不管是否下订单,因此您希望它是LEFT JOIN
。如果您执行了INNER JOIN
,则只会导致发生订单的事件,而不是所有事件。所以现在,您的查询如下所示:
SELECT *
FROM events e
LEFT JOIN orders o
events
和orders
将在location_id
上进行联接,因此将其添加到联接的ON
子句中:
SELECT *
FROM events e
LEFT JOIN orders o
ON e.location_id = o.location_id
由于订单也基于时间而关联,因此您还需要将其添加到ON
子句中:
SELECT *
FROM events e
LEFT JOIN orders o
ON e.location_id = o.location_id
AND e.start_time <= o.time_placed -- event starts before/at order
AND e.end_time >= o.time_placed -- event ends after/at order
那将正确地加入表格。接下来,您需要将它们分组。由于您需要event
进行分组,因此您将在`id:
event
列上分组
SELECT *
FROM events e
LEFT JOIN orders o
ON e.location_id = o.location_id
AND e.start_time <= o.time_placed -- event starts before/at order
AND e.end_time >= o.time_placed -- event ends after/at order
GROUP BY e.id
最后,使用所需的字段填充SELECT
,使用COUNT
获取每个事件的订单数:
SELECT e.id,
COUNT(o.id) AS order_count
FROM events e
LEFT JOIN orders o
ON e.location_id = o.location_id
AND e.start_time <= o.time_placed -- event starts before/at order
AND e.end_time >= o.time_placed -- event ends after/at order
GROUP BY e.id
如果您想要events
表中的其他字段(start_time
,end_time
),则需要将其添加到SELECT
和GROUP BY
部分中