将三个JOIN查询合并为一个(UNION)时出错

时间:2014-03-12 11:02:17

标签: sql ms-access union

我正在尝试将三个查询合并到一个UNION查询中,但是我收到一个UNION语法错误

SELECT distinct(db_tbl_full.db_tbl_customers_C_ID), LOC, 
USER_TYPE, db_tbl_customers_Record_Count, t_count_m1
FROM db_tbl_full 
LEFT JOIN qry_cs_t_count_m1 ON db_tbl_full.db_tbl_customers_C_ID=qry_cs_t_count_m1.db_tbl_customers_C_ID

UNION

SELECTdistinct(db_tbl_full.db_tbl_customers_C_ID, LOC, 
USER_TYPE, nm1.db_tbl_customers_Record_Count, t_count_m1, t_count_m2
FROM db_tbl_full 
LEFT JOIN qry_cs_t_count_m2 
ON nm1.db_tbl_customers_C_ID=qry_cs_t_count_m2.db_tbl_customers_C_ID

UNION

SELECT distinct(db_tbl_full.db_tbl_customers_C_ID), LOC, 
USER_TYPE, nm2.db_tbl_customers_Record_Count, t_count_m1, 
t_count_m2, t_count_m3
FROM db_tbl_full 
LEFT JOIN qry_cs_t_count_m3 
ON nm2.db_tbl_customers_C_ID=qry_cs_t_count_m3.db_tbl_customers_C_ID
ORDER BY nm2.db_tbl_customers_C_ID;

非常感谢任何纠正语法的帮助。

1 个答案:

答案 0 :(得分:0)

不同的子查询中有不同数量的列。试试这个:

SELECT distinct db_tbl_full.db_tbl_customers_C_ID, LOC, 
       USER_TYPE, db_tbl_customers_Record_Count, t_count_m1,
       NULL as t_count_m2, NULL as t_count_m3
FROM db_tbl_full LEFT JOIN
     qry_cs_t_count_m1
     ON db_tbl_full.db_tbl_customers_C_ID = qry_cs_t_count_m1.db_tbl_customers_C_ID

UNION

SELECT distinct db_tbl_full.db_tbl_customers_C_ID, LOC, 
       USER_TYPE, nm1.db_tbl_customers_Record_Count, t_count_m1, t_count_m2, NULL as t_count_m3
FROM db_tbl_full LEFT JOIN
     qry_cs_t_count_m2 
     ON nm1.db_tbl_customers_C_ID = qry_cs_t_count_m2.db_tbl_customers_C_ID

UNION

SELECT distinct db_tbl_full.db_tbl_customers_C_ID, LOC, 
       USER_TYPE, nm2.db_tbl_customers_Record_Count, t_count_m1, 
       t_count_m2, t_count_m3
FROM db_tbl_full LEFT JOIN
     qry_cs_t_count_m3 
     ON nm2.db_tbl_customers_C_ID = qry_cs_t_count_m3.db_tbl_customers_C_ID
ORDER BY nm2.db_tbl_customers_C_ID;

您还了解distinct周围的括号无效。 distinct适用于整行。