计算来自不同列的记录(MySQL / php)

时间:2016-03-02 11:58:57

标签: php mysql

我有一张这样的表

     id  |  block1  |  block2  |  block3
-----------------------------------------------
     1   |  John    |  John    |
     2   |  Mark    |          |
     3   |          |  Frank   |  Frank

我怎么算数约翰,马克和弗兰克在桌子上有多少人? ES。

John - 2
Mark - 1
Frank - 2

我使用下面的查询,但仅适用于一列,我不知道所有列的结果是否相同。我认为这是一个有用的查询因为我读过可能有结果可能是上个月或一年

SELECT block1,
COUNT(*) AS total
FROM table
GROUP BY block1
ORDER BY total DESC;
谢谢你 (对不起我的英文)

2 个答案:

答案 0 :(得分:1)

您可以使用UNION ALL取消忽略该表格,然后应用分组:

SELECT block, COUNT(*) AS 'total'
FROM (
   SELECT block1 AS block
   FROM mytable    

   UNION ALL

   SELECT block2
   FROM mytable       

   UNION ALL

   SELECT block3
   FROM mytable) AS t
GROUP BY block

答案 1 :(得分:0)

单独选择列并使用UNION合并它们。然后COUNT他们。你可以试试这个 -

SELECT col_block, COUNT(col_block) FROM (
(SELECT block1 col_block,
FROM table)
UNION ALL
(SELECT block2 col_block,
FROM table)
UNION ALL
(SELECT block3 col_block,
FROM table)) tbl
GROUP BY col_block