如何知道计数数据并显示在多个表中

时间:2016-05-28 18:46:15

标签: mysql

我的查询有问题。

这是我的第一张表,"订单":

id_order  id_event
------------------
    1       12    
    2       12  

这是我的第二张表," event_table":

id_event  event_name      id_eo
--------------------------------
    12        Festival      1
    13        Music         1

我想要的就是这样的结果:

Festival : 2 order
Music    : 0 order

这是我到目前为止所做的:

SELECT
  (SELECT
    COUNT(*)
  FROM
  ORDER) AS jumorder,
  event_name
FROM
ORDER p
  INNER JOIN EVENT
    ON (p.id_event = event.id_event)
WHERE event.id_eo = '1'

6 个答案:

答案 0 :(得分:2)

使用LEFT JOINCONCAT,您可以获得帖子中提到的预期结果。

SELECT CONCAT(E.event_name, ": ", COUNT(O.id_event), " order") Result
FROM `event_table` E
LEFT JOIN `order` O ON O.id_event = E.id_event
WHERE id_eo = '1'
GROUP BY E.event_name;

结果

Festival: 2 order
Music: 0 order

SQL小提琴:http://sqlfiddle.com/#!9/006c09/4

答案 1 :(得分:1)

您需要按事件分组:

select e.event_name, count(*) as jumorder 
from order p
inner join event e ON p.id_event = e.id_event
where e.id_eo = '1'
group by e.id_event, e.event_name

答案 2 :(得分:1)

希望这有帮助。

SELECT
      event_name AS EventName,
     COUNT(*) AS NoOfOrders
FROM event_table AS ET
LEFT JOIN order AS O
ON ET.id_order= O.id_order 
GROUP BY  event_name 

答案 3 :(得分:1)

在反引号中包含单词顺序,并按事件添加组:

SELECT count(*) as jumorder,
        event_name from `order` p 
INNER JOIN event ON p.id_event=event.id_event
WHERE event.id_eo='1'
GROUP BY e.id_event, e.event_name

答案 4 :(得分:1)

使用left join

select count(p.id_event) as jumorder, event_name
from event e left join
     order p 
     on p.id_event = e.id_event 
where e.id_eo = '1'
group by event_name;

注意:

  • 对于left joinevent表必须是第一个。
  • order是一个非常糟糕的表名,因为它是一个SQL保留字。
  • count()需要计算匹配(第二)表中的列。

答案 5 :(得分:1)

尝试查询

SELECT CONCAT(A.event_name,' : ' ,COUNT(B.id_event),' order') Result 
FROM event_table A LEFT JOIN `order` B 
ON A.id_event = B.id_event AND A.id_eo = '1'  GROUP BY A.id_event

注意:尽量避免像'order','like'等字样,因为它已经为mysql保留了..

检查FIDDLE