简体   繁体   中英

Mysql query to count from multiple columns

I have sql query like that:

SELECT
   CONCAT(t1.a, t2.a, t2.b, t3.a, t4.a, t4.b) AS val
FROM
   t1 
   LEFT JOIN t2 ON ...
   LEFT JOIN t3 ON ...
   LEFT JOIN t4 ON ...

val output as: 0,1,0,1,2,1 OR 1,2,0,1,0,2,... (includes 0,1,2 in random order)

I want count total for each number, as: 0=>2, 1=>3, 2=>1, without PHP code

You could simply wrap your existing query in a subquery, and make an outer query that counts the occurrences;

SELECT 
  LENGTH(val) - LENGTH(REPLACE(val, '0', '')) zeros,
  LENGTH(val) - LENGTH(REPLACE(val, '1', '')) ones,
  LENGTH(val) - LENGTH(REPLACE(val, '2', '')) twos
FROM (
  SELECT
    CONCAT(t1.a, t2.a, t2.b, t3.a, t4.a, t4.b) AS val
  FROM
    t1 
    LEFT JOIN t2 ON ...
    LEFT JOIN t3 ON ...
    LEFT JOIN t4 ON ...
);

You need to use UNION ALL for this.

SELECT tbl.col1, COUNT(tbl.col1)
FROM (
  SELECT t1.a as col1
    FROM t1
  UNION ALL
  SELECT t2.a as col1
    FROM t2
  UNION ALL
  SELECT t3.a as col1
    FROM t3
   ...
) tbl
GROUP BY tbl.col1;

SQLFIDDLE DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM