【发布时间】: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? -
为什么是
2?table2有两行event_id = 1。 -
对不起@ajmedway:这是一个错误。我需要在 where 条件下使用 time_name
-
@Praveen:是的。表 2 将有表 1 的多个值。这就是要求
-
@Corner 请检查我的答案,如果它适合你,请点赞/接受,谢谢!