I got a users table in my project
id | name | user_group
-----+------------+----------------
1 | name | 1
2 | name | 1
3 | name | 2
4 | name | 2
5 | name | 2
6 | name | 2
7 | name | 2
------------------------------------
Each user is associated with a group
Also users can upload images to the site so I got a table for images.
id | image_name | user_id | uploaded_date
------+---------------------+---------------+--------------------------
1 | dder.jpg | 1 | 2014-12-12 00:00:00
2 | dder.jpg | 1 | 2014-12-12 00:00:00
3 | dder.jpg | 2 | 2014-12-12 00:00:00
4 | dder.jpg | 3 | 2014-12-12 00:00:00
5 | dder.jpg | 6 | 2014-12-12 00:00:00
6 | dder.jpg | 7 | 2014-12-12 00:00:00
7 | dder.jpg | 7 | 2014-12-12 00:00:00
8 | dder.jpg | 5 | 2014-12-12 00:00:00
9 | dder.jpg | 2 | 2014-12-12 00:00:00
10 | dder.jpg | 1 | 2014-12-12 00:00:00
------------------------------------------------------------------------
Now my question is I needs to get the list of images uploaded by user_group=2 in the DESC of uploaded_date
Can anyone please help me with a simple query ?
Thanks in advance
One possible approach:
SELECT i.*
FROM images i
INNER JOIN users u
ON i.user_id = u.id
WHERE u.user_group = 2
ORDER BY i.uploaded_date DESC
Demo . For performance, it's important to have a foreign key set on user_id
column in images
table, that references id
column in users
table.
You can solve this like so: http://sqlfiddle.com/#!2/28a18/1
SELECT img.image_name
FROM images img
INNER JOIN users usr
ON img.user_id = usr.id
WHERE usr.user_group = 2
ORDER BY img.uploaded_date DESC
However, if you want to have more than one user_group assigned to a user at some point, you should have something like this: http://sqlfiddle.com/#!2/8f938/1
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.