tags:

views:

44

answers:

1

Hello

Since i'm a poor sql developer, i need support to write a sql query for the following scenario (just a simplified example of my situation):
i've got 3 tables, say employe table,department table and companybranch table. the dept column , on the employe table is a fk on the department table; the branch column on the department table is a fk on the companybranch table. Finally more employee are "marked" with the same value . There's a way to select all employes with the same "mark" and, in the same query, check that they work in the same company branch ?

thank you in advance

Stefano

+1  A: 

Something like this would work:

SELECT * 
FROM employee e
JOIN department d ON e.dept = d.id
JOIN companybranch b ON d.branch = b.id
WHERE e.mark = 'mark here'
AND b.id = 'Branch id here'

EDIT

if you can't filter by branch, cause you don't know its value, then you can make a DISTINCT query, to check the differents b.id

SELECT DISTINCT b.id branch_id
FROM employee e
JOIN department d ON e.dept = d.id
JOIN companybranch b ON d.branch = b.id
WHERE e.mark = 'mark here'

this is another option, you can check

SELECT inside.branch_id, COUNT(*) total
FROM (
    SELECT b.id branch_id
    FROM employee e
    JOIN department d ON e.dept = d.id
    JOIN companybranch b ON d.branch = b.id
    WHERE e.mark = 'mark here'
    ) inside
GROUP BY inside.branch_id
Jhonny D. Cano -Leftware-
thank you for your answer, but my problem is to find a way to verify all the records have a the same b.id indipendently by its value. In other words :SELECT * FROM employee e JOIN department d ON e.dept = d.id JOIN companybranch b ON d.branch = b.id WHERE e.mark = 'mark here' having the same b.id i don't know if b.id is miami or los angeles i just want to be sure all records have the same b.id. Can i do such a thing in a single query or shall add a check with a programming language?thanks again for your answer
Stefano
But if you filter by b.id, aren't you ensuring they are all equal? see my updated answer
Jhonny D. Cano -Leftware-
you are right, i can't filter the branch because i don't know its value. The rule is : "all the employee grouped by the same mark should be in the same branch". The example i've used migth be a bit confusing about why i don't use the branch to mark employees, but that just an example. Anyway the schema doesn't have any constraint about it , so i think i'll do as you suggest, i'll count the branches occurrencies and throw an exception if there are nultiple values.Thank you again for your support
Stefano