Question

I have the following entities

Department has many Users and users have many Records.

Now i want that users can see all records of same department.

I am confused do i need to make relation ship between Department and Records or it can be traversed through users

Was it helpful?

Solution

JOINS are efficient then sub-queries.

This is what you can try using INNER JOIN

SELECT * FROM records AS r
INNER JOIN
users AS u ON (r.user_id = u.user_id)
WHERE u.department_id = 1

OTHER TIPS

You can use subquery:

SELECT * FROM Records WHERE user_id IN (SELECT User.id FROM User WHERE department_id = 123)

You just need a 1-n relation from department to users and a 1-n relation from users to records. Then you know which department a record belongs to by looking up which department the user belongs to that this record is assigned to.

If user has id_department and record has id_user then you can get all records that relates to certain department.

sample code:

SELECT a.batsman_id,a.matchs,a.hundreds,b.country_type, c.player_name
FROM batsman a  INNER JOIN countrycode b ON a.country_code=b.country_code
        INNER JOIN players c ON a.player_id=c.player_id
        ORDER BY a.batsman_id; 

screen shots:

countrycode

players

batsman

output

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top