0

I am trying to display all records from table1 even if the catid not existing in table2 (all employee in table2 should have all catid from table1 with 0 days if not exising in table2) with the following sql query but getting an error

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

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

table1:

catid
  1
  2
  3

table2:

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

expected result:

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

4 Answers4

0

That is not the function of the union statement. Union statement does a set like capability which merging two sets. What you are looking for a is a join with the table 1 where you do a count and group by catid. Your data model to achieve this output itself is grievously wrong ;)

select employeeid, catid, sum(days) from table1, table2 group by employeeid, catid;
  • this retrieves all catid from table1 and also the empid but days are all same value. Actually days are count(*) not an actual column in table2 – Hafsa Abdul gafoor Oct 27 '15 at 06:27
0

You just need a LEFT JOIN:

    Select tab2.empid, tab2.catid, ifnull(tab2.days, 0)
    from tab2 
    left join tab1 on tab2.catid = tab1.catid

Please note : While doing a UNION the number and type of the columns present in the first select should be the same as the next Selects.

So you need to first make the select columns in sync first.

Sashi Kant
  • 13,277
  • 9
  • 44
  • 71
0

can you check this and add empid similarly.  

SELECT TABLE1.CATID, IFNULL(TABLE2.DAYS,0) FROM table1 LEFT OUTER JOIN
table2 ON table1.catid = table2.catid
Shaminder Singh
  • 1,283
  • 2
  • 18
  • 31
Don
  • 102
  • 1
  • 10
0

Please use LEFT JOIN with IFNULL.

Select table2.empid, table1.catid, IFNULL(table2.days, 0) from table2 
LEFT JOIN table1 ON table2.catid = table1.catid;