MYSQL查询:组合列并获取计数

时间:2012-11-05 23:45:43

标签: mysql

我有大约9个包含相同类型字段的表。我想将其中的9个首先组合在一起,然后在该组合列中获得独特值的独特计数。这是我到目前为止所尝试过的,但无济于事。我不是也不确定这是返回这个值的最有效方法吗?

SELECT COUNT(DISTINCT aircraft_id) FROM 
(
SELECT aircraft_id FROM database.a_message UNION ALL
SELECT aircraft_id FROM database.b_message UNION ALL
SELECT aircraft_id FROM database.c_message UNION ALL
SELECT aircraft_id FROM database.d_message UNION ALL
SELECT aircraft_id FROM database.e_message UNION ALL
SELECT aircraft_id FROM database.f_message UNION ALL
SELECT aircraft_id FROM database.g_message UNION ALL
SELECT aircraft_id FROM database.h_message UNION ALL
SELECT aircraft_id FROM database.i_message
) ;

1 个答案:

答案 0 :(得分:0)

SELECT DISTINCT aircraft_id,count(aircraft_id) FROM 
(
SELECT aircraft_id FROM database.a_message UNION ALL
SELECT aircraft_id FROM database.b_message UNION ALL
SELECT aircraft_id FROM database.c_message UNION ALL
SELECT aircraft_id FROM database.d_message UNION ALL
SELECT aircraft_id FROM database.e_message UNION ALL
SELECT aircraft_id FROM database.f_message UNION ALL
SELECT aircraft_id FROM database.g_message UNION ALL
SELECT aircraft_id FROM database.h_message UNION ALL
SELECT aircraft_id FROM database.i_message
) group by aircraft_id;

select aircraft_id,count(aircraft_id)
(
SELECT DISTINCT aircraft_id FROM 
(
SELECT aircraft_id FROM database.a_message UNION ALL
SELECT aircraft_id FROM database.b_message UNION ALL
SELECT aircraft_id FROM database.c_message UNION ALL
SELECT aircraft_id FROM database.d_message UNION ALL
SELECT aircraft_id FROM database.e_message UNION ALL
SELECT aircraft_id FROM database.f_message UNION ALL
SELECT aircraft_id FROM database.g_message UNION ALL
SELECT aircraft_id FROM database.h_message UNION ALL
SELECT aircraft_id FROM database.i_message
)
) group by aircraft_id;