简体   繁体   English

从2个MySQL表中获取数据

[英]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的表和一个名为Users的表。 UserRole contains the UserID and the RoleID. UserRole包含UserID和RoleID。 I can select all the users from UserRole that have the RoleID "16" (16 = Administrator). 我可以从UserRole中选择所有RoleID为“ 16”(16 =管理员)的用户。 How do I use the UserID I get from UserRole to access the data in the Users table? 如何使用从UserRole获得的UserID访问Users表中的数据?

(note - I'm new to this whole PHP mySQL thing :D) (注意-我是整个PHP mySQL的新手:D)

Divyesh Savaliya is correct but prefer use JOIN : Divyesh Savaliya是正确的,但更喜欢使用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. 而且,首先指定“ id”对于人们快速解释是更好的选择。 This way you directly know where is the id. 这样,您可以直接知道ID在哪里。

Last but not least, it cant be usefull to specify if an ID is a foreign key. 最后但并非最不重要的一点是,指定ID是否为外键没有用。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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