I have two tables Employee and Department. I want to write a query that can give me data from both the tables with the count of the values.
create table Employee(EmpID text);
insert into Employee values("A");
insert into Employee values("B");
insert into Employee values("C");
create table Departments(EmpID text);
insert into Departments values("B");
insert into Departments values("C");
insert into Departments values("D");
OUTPUT
| EMP_ID | COUNT |
|-------- |------- |
| A | 1 |
| B | 2 |
| C | 2 |
| D | 1 |
Searched everywhere, but didn't find anything helpful yet. Here is the playgroundhttps://paiza.io/projects/TdkdHannoclhbevdqpFlKw?language=mysql
Below is the query I m trying out, using the full outer join as it gives all matching and unmatching rows
SELECT *FROM Employee outer join Departments on Employee.EmpID=Departments.EmpID
This is quite a strange data model. But use union all
and then group by
:
select empid, count(*)
from (select empid from employee union all
select empid from department
) e
group by empid;
That you have empid
in department
that does not match empid
s in employee
is a data modeling problem . You should have a foreign key relationship from department
to employee
to ensure that this can never happens. Your database lacks relational integrity.
select empid, count(empid)
from (
select empid from employee
union all
select empid from department
) e
group by empid;
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.