我正在尝试使用id
从50个表格中选择FIND_IN_SET
。是否可以使用LEFT JOIN
以外的其他方式? 我只给了3张桌子,因为50张桌子不合适。
注意:每个表中都有about_education
列。
下面的代码无法正常工作,那么我还要怎么做才能避免使用一千行代码?
nose_1
|id|class|about_education|
| 1| 1| a01|
| 2| 0| a02|
coins_2
|id|class|about_education|
| 1| 1| a01|
| 2| 0| a02|
money_3
|id|class|about_education|
| 1| 1| a01|
| 2| 1| a10|
SELECT COUNT(id) AS id FROM nose_1, coins_2, money_3 WHERE class=1 AND FIND_IN_SET('a01', about_education)");
SELECT COUNT(id) AS id FROM nose_1, coins_2, money_3 WHERE class=1 AND FIND_IN_SET('a02', about_education)");
SELECT COUNT(id) AS id FROM nose_1, coins_2, money_3 WHERE class=1 AND FIND_IN_SET('a02', about_education)");
SELECT COUNT(id) AS id FROM nose_1, coins_2, money_3 WHERE class=1 AND FIND_IN_SET('a03', about_education)");
SELECT COUNT(id) AS id FROM nose_1, coins_2, money_3 WHERE class=1 AND FIND_IN_SET('a04', about_education)");
SELECT COUNT(id) AS id FROM nose_1, coins_2, money_3 WHERE class=1 AND FIND_IN_SET('a05', about_education)");
SELECT COUNT(id) AS id FROM nose_1, coins_2, money_3 WHERE class=1 AND FIND_IN_SET('a06', about_education)");
SELECT COUNT(id) AS id FROM nose_1, coins_2, money_3 WHERE class=1 AND FIND_IN_SET('a07', about_education)");
SELECT COUNT(id) AS id FROM nose_1, coins_2, money_3 WHERE class=1 AND FIND_IN_SET('a08', about_education)");
SELECT COUNT(id) AS id FROM nose_1, coins_2, money_3 WHERE class=1 AND FIND_IN_SET('a09', about_education)");
SELECT COUNT(id) AS id FROM nose_1, coins_2, money_3 WHERE class=1 AND FIND_IN_SET('a10', about_education)");
输出:3,0,0,0,0,0,0,0,0,1
答案 0 :(得分:0)
您需要编写所有表的子查询UNION ALL
,然后使用count
的{{1}}函数从ID中获取计数。
CASE WHEN
sqlfiddle:http://sqlfiddle.com/#!9/6a87fa/4
结果
SELECT
COUNT(CASE WHEN about_education = 'a01' and class = 1 then 1 else null end) a01,
COUNT(CASE WHEN about_education = 'a02' and class = 1 then 1 else null end) a02,
COUNT(CASE WHEN about_education = 'a03' and class = 1 then 1 else null end) a03,
COUNT(CASE WHEN about_education = 'a04' and class = 1 then 1 else null end) a04,
COUNT(CASE WHEN about_education = 'a05' and class = 1 then 1 else null end) a05,
COUNT(CASE WHEN about_education = 'a06' and class = 1 then 1 else null end) a06,
COUNT(CASE WHEN about_education = 'a07' and class = 1 then 1 else null end) a07,
COUNT(CASE WHEN about_education = 'a08' and class = 1 then 1 else null end) a08,
COUNT(CASE WHEN about_education = 'a09' and class = 1 then 1 else null end) a09,
COUNT(CASE WHEN about_education = 'a10' and class = 1 then 1 else null end) a10
FROM
(
SELECT id,class,about_education from nose_1
UNION ALL
SELECT id,class,about_education FROM coins_2
UNION ALL
SELECT id,class,about_education FROM money_3
) t
答案 1 :(得分:0)
union all
是正确的方法,但是我认为除非您确实想要列中的值,否则我建议进行定期聚合:
select about_education, count(*)
from (select id, class, about_education from nose_1
union all
select id, class, about_education from coins_2
union all
select id, class, about_education from money_3
) t
where class = 1
group by about_education;