【问题标题】:How to get count from first table field when joining加入时如何从第一个表字段中获取计数
【发布时间】:2015-09-23 09:57:41
【问题描述】:

我在数据库中有两个 mysql 表。表 1 和表 2。

表1

event_id  |  event_name
------------------------
1         |  event1
------------------------
2         |  event2
------------------------
3         |  event3
------------------------

表2

time_id  |  event_id  |  time_name  |  status  |
-----------------------------------------------
1        |  1         |   morning   |  paid    |
------------------------------------------------
2        |  1         |   morning   |  not paid |
------------------------------------------------
3        |  2         |   afternoon |  paid     |
-------------------------------------------------

在基于event_id 加入这两个表后,我想从第一个表中获取event_id 的计数。为什么我需要加入是因为,我需要在 time_name 中有一个 WHERE 条件。

到目前为止我的查询是这样的,

SELECT count(`table1`.`event_id`) FROM `table1` JOIN `table2` ON `table2`.`event_id` = `table1`.`event_id` WHERE `table2`.`time_name` = 'morning'

但我得到的结果是 2。为什么会这样?我要求的结果是 1

【问题讨论】:

  • WHERE中需要如何使用time_id
  • 为什么是2table2 有两行 event_id = 1
  • 对不起@ajmedway:这是一个错误。我需要在 where 条件下使用 time_name
  • @Praveen:是的。表 2 将有表 1 的多个值。这就是要求
  • @Corner 请检查我的答案,如果它适合你,请点赞/接受,谢谢!

标签: mysql join


【解决方案1】:

您正在使用 event_id 字段对表 2 进行 INNER JOIN(仅获取 table2 具有 event_id 的行),因此您需要使用 LEFT JOIN,这将返回 table1 中的所有行(除了那些排除在WHERE) 并加入 table2 中具有匹配 event_id 的任何行(否则在其位置返回 NULL 字段):

SELECT count(`table1`.`event_id`) AS t1_event_count
FROM `table1`
LEFT JOIN `table2` ON `table2`.`event_id` = `table1`.`event_id`
WHERE `table2`.`time_name` = 'morning'

【讨论】:

  • 非常感谢@ajmedway
猜你喜欢
  • 2014-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 2013-12-05
相关资源
最近更新 更多