简体   繁体   中英

many-to-many query mysql

I have 3 tables: users

+-----+--------+
| id  |  name  |
+-----+--------+
|  1  |  John  |
+-----+--------+
|  2  |  Mike  |
+-----+--------+

files

+-----+--------+
|  id |  file  |
+-----+--------+
|  22 | file1  |
+-----+--------+
|  23 | file2  |
+-----+--------+

and table relationship usersfiles

+-------+--------+
| usrID | fileID |
+-------+--------+
|   1   |   22   |
+-------+--------+
|   2   |   22   |
+-------+--------+
|   2   |   23   |
+-------+--------+

How should the mysql query for this question look like?

Select all files enabled for current user. Answer for this example would look like this: for user John enabled just file1 . For user Mike enabled files file1 and file2 .

这是一个简单的联接:

select files.id from users join usersfile on users.id=usrid join files on fileID=files.id where userid= <userid>

用这个

SELECT name, file FROM users,userfiles, files WHERE users.id = userfiles.usrid AND usersfiles.fileid = files.id;

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