简体   繁体   中英

How to get the data I want in MySQL in one query or in PHP?

The table fields and its data:

auto_id   user_id  file_id
1         1         1
2         1         13
3         1         14
4         4         1
5         5         1
6         8         18
7         8         51
8         8         31

And what I want is:

userFiles[user_id] = 'file_id';

Eg:

userFiles[1] = '1,13,14';
userFiles[4] = '1';
userFiles[5] = '1';
userFiles[8] = '18,51,31';

Thank you very much!!

SELECT user_id, GROUP_CONCAT(file_id)
FROM yourtable
GROUP BY user_id

is the easy way to do it, if there aren't too many records - group_concat has a length limit of 1024 bytes (default, but is configurable).

The SQL query you can use is straightforward for each ID:

"select file_id from TABLE where user_id = " . $user_id;

Load your answers into an array, then:

$string = implode(",",$answers);

Put the whole thing in a for loop around your user_id and assign to your userFiles array.

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