0

I have 2 table first table. employee( empid- primary key ,empname) eg: employee table

1 john 

2 martyn 

3 davis 

second table documents(empid,documentname) eg :

1 address.doc 

1 worksheet.doc 

1 salaryslip.doc 

3 address.doc 

each employee have only one entry in employee table but in document table , zero or more entries are inserted for each employee.

i want to write a query that gives an output shown in below

empid empname documentflag 
1 john true 
2 martyn null 
3 davis true 

that is, if documents table have at least one entry for an employee ,then set corresponding document flag is true. otherwise set document value as null. is there any efficient way using joins. Thanks in advance

1
  • You could try a combination of UPDATE and IF NOT NULL ... Commented Sep 29, 2010 at 10:08

2 Answers 2

2

You can do this with a LEFT JOIN to include the documents table, a GROUP BY so that you only get 1 employee per row, and an IF() construct to output the values you want for documentflag.

SELECT e.empid, e.empname, IF(d.empid IS NULL, NULL, TRUE) `documentflag`
FROM employee e
LEFT JOIN documents d ON (d.empid = e.empid)
GROUP BY e.empid
Sign up to request clarification or add additional context in comments.

Comments

0
SELECT
    empid, 
    empname,
    documentFlag
FROM employee emp 
LEFT OUTER JOIN 
(SELECT doc.empid, count(doc.empid)as documentFlag
 FROM documents doc Group by empid) X
ON emp.empid = X.empid

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.