在mysql中的两个表中基于一个相同的列计算两个列值

时间:2013-09-16 04:32:31

标签: mysql count multiple-columns

情况是这样的:

表一(短信)

id  |  t_id  |  sms_text
1   |   200  |  some text here ...
2   |   201  |  some text here ...
3   |   202  |  some text here ...
4   |   201  |  some text here ...
5   |   202  |  some text here ...
6   |   202  |  some text here ...

表二(msg)

id  |  t_id  |  msg_text
1   |   201  |  some text here ...
2   |   202  |  some text here ...
3   |   200  |  some text here ...
4   |   200  |  some text here ...
5   |   202  |  some text here ...
6   |   200  |  some text here ...

现在我想要类似的结果

计算结果(短信+信息)

t_id | count result
200  |  4
201  |  3
202  |  5

有可能吗?如果是,怎么样?

1 个答案:

答案 0 :(得分:2)

您可以 - 例如 - 使用UNION ALL从两个表中获取t_id,只需COUNT个;

SELECT t_id, COUNT(*) `count`
FROM (
  SELECT t_id FROM Table1
  UNION ALL
  SELECT t_id FROM Table2
) dummy
GROUP BY t_id

An SQLfiddle to test with