简体   繁体   中英

MySQL Select values in table depending on another table

I have a table 'Staff' with details of all Staff. 'StaffID' included.

Then I have a table 'StaffRole' which has 'StaffID' and 'RoleID'

I want to do something like this: Select * From Staff Where RoleID=1;

But I'm not sure if I can do this as RoleID is not in the Staff table.

Anyone know the correct syntax? Any feedback is appreciated.

Try this:

SELECT * FROM staff s
WHERE EXISTS(
   SELECT 'ROLE'
   FROM staffrole r
   WHERE r.staffid = s.staffid
   AND r.roleid = 1
)

In alternative:

SELECT * FROM staff s
JOIN staffrole r
ON r.staffid = s.staffid
WHERE r.roleid = 1

Use a join:

select s.*
from staffrole r
join staff s
  on s.staffid = r.staffid
where roleid = 1

An index on staffrole(roleid) should make it perform better.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM