简体   繁体   中英

Getting data from 2 mySQL tables

So - I am trying to make a script that connects to an already existing database. There is a table called UserRole and a table called Users. UserRole contains the UserID and the RoleID. I can select all the users from UserRole that have the RoleID "16" (16 = Administrator). How do I use the UserID I get from UserRole to access the data in the Users table?

(note - I'm new to this whole PHP mySQL thing :D)

Divyesh Savaliya is correct but prefer use JOIN :

SELECT u.*
FROM User u
INNER JOIN UserRole ur ON u.UserID = ur.UserID
WHERE ur.RoleID = 16;

I hope you dont use upper + lower case in your DB table names and columns. Prefer underscores. Moreover, specifying first the "id" is better for a fast interpretation by people. This way you directly know where is the id.

Last but not least, it cant be usefull to specify if an ID is a foreign key.

Example :

SELECT u.*
FROM user u
INNER JOIN user_role ur ON u.id_user = ur.fk_id_user
WHERE ur.id_role = 16;
SELECT *
FROM User 
LEFT JOIN UserRole 
ON User.userID = UserRole.userID Where RoleID= 16;

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