来自2个不同表的Count()

时间:2011-05-02 22:33:51

标签: php mysql count

我有2个不同的表admin_reservations和calendar_events

admin_reservation:

ID,

FULL_NAME,

reservation_date,

reservation_time


John 03.05.2011 17:00

Mary 03.06.2011 12:00


calendar_events:

ID,

用户名,

reservation_date,

reservation_time


john.boy 02.05.2011 15:00

suzie 03.05.2011 07:00


我想这样算:

03.05.2011 2

02.06.2011 1

03.06.2011 1

4 个答案:

答案 0 :(得分:1)

试试这个:

SELECT dt,COUNT(id) tot FROM
(
    SELECT id,full_name fn,reservation_date dt,reservation_time
    FROM admin_reservations
    UNION ALL
    SELECT id,username fn,reservation_date dt,reservation_time
    FROM calendar_events
) GROUP BY dt ORDER BY tot desc

答案 1 :(得分:0)

我没有太多时间,但我想分享一下:

执行a(选择表格A UNION上的全部选择表格B上的所有内容)GOUP BY日期。

MySQL UNION

MySQL GROUP BY

但要小心。这不可能很快=)

答案 2 :(得分:0)

将每个表的计数相加可能会更快,但您应该比较执行计划:

SELECT reservation_date, SUM(date_count) FROM
(
    SELECT reservation_date, COUNT(*) AS date_count
    FROM admin_reservations
    GROUP BY reservation_date
    UNION ALL
    SELECT reservation_date, COUNT(*) AS date_count
    FROM calendar_events
    GROUP BY reservation_date
) GROUP BY reservation_date

答案 3 :(得分:0)

感谢@Marco的代码,但我修改了一些代码以便它可以工作:

SELECT dt,COUNT(*) AS tot FROM(
  (
    SELECT reservation_date AS dt
    FROM admin_reservations
  ) 
    UNION ALL    
  (
   SELECT reservation_date AS dt
   FROM calendar_events
  )
)AS foo GROUP BY dt ORDER BY dt