Mysql选择union错误

时间:2015-10-27 14:27:15

标签: mysql union

我正在尝试显示table1中的所有记录,即使table2中不存在catid(table2中的所有employee都应该具有table1中的所有catid,如果没有在table2中存在,则为0天),但是出现以下sql查询但是收到错误:

Error Code: 1054. Unknown column 'catid' in 'group statement'

SQL

select empid,days from table2 
union 
select catid from table1 
group by empid, catid;

表1

catid
1
2
3

table2
empid catid days (computed column count(*))
1000    1    1
1000    3    1

预期结果:

empid  catid  days
1000    1    1
1000    2    0 <---catid 2 and days 0 if catid is not existing in table2 for empid 1000
1000    3    1

1 个答案:

答案 0 :(得分:2)

你可以这样做:

表1:

mysql> SELECT * FROM table1;
+-------+
| catid |
+-------+
|     1 |
|     2 |
|     3 |
+-------+
3 rows in set (0.00 sec)

表2:

mysql> SELECT * FROM table2;
+-------+-------+
| empid | catid |
+-------+-------+
|  1000 |     1 |
|  1000 |     3 |
|  1001 |     1 |
|  1002 |     2 |
|  1002 |     3 |
+-------+-------+
5 rows in set (0.00 sec)

查询:

SELECT
    t2.empid,
    t1.catid
    ,COUNT(t3.empid) as days
FROM table1 AS t1
LEFT JOIN (SELECT 
                DISTINCT empid,t1.catid 
            FROM table2 AS t2 
            LEFT JOIN table1 AS t1 ON (t1.catid>0)
            ) AS t2 -- Getting all empids from table2 and catids from table1
ON (t1.catid=t2.catid)
LEFT JOIN table2 AS t3 ON (t2.empid=t3.empid AND t3.catid=t2.catid)
GROUP BY t2.empid,t2.catid
ORDER BY t2.empid,t2.catid;

测试:

mysql> SELECT
    -> t2.empid,
    ->     t1.catid
    -> ,COUNT(t3.empid) as days
    -> FROM table1 AS t1
    -> LEFT JOIN (SELECT DISTINCT empid,t1.catid FROM table2 AS t2 LEFT JOIN table1 AS t1 ON (t1.catid>0)) AS t2
    -> ON (t1.catid=t2.catid)
    -> LEFT JOIN table2 AS t3 ON (t2.empid=t3.empid AND t3.catid=t2.catid)
    -> GROUP BY t2.empid,t2.catid
    -> ORDER BY t2.empid,t2.catid;
+-------+-------+------+
| empid | catid | days |
+-------+-------+------+
|  1000 |     1 |    1 |
|  1000 |     2 |    0 |
|  1000 |     3 |    1 |
|  1001 |     1 |    1 |
|  1001 |     2 |    0 |
|  1001 |     3 |    0 |
|  1002 |     1 |    0 |
|  1002 |     2 |    1 |
|  1002 |     3 |    1 |
+-------+-------+------+