1

I have an images table which stores an image id, title, the user who uploads it, a timestamp and file extension.

I also have a views table which records when an image has been viewed. the columns are id, image id, timestamp and the user who viewed the image.

What i need and have no idea how to do is to run an SQL query which will return a set of images in order of the most viewed.

I've been looking around on here and Google but just don't know what to actually search.

4

2 回答 2

4
SELECT images.*, count(views.view_id) view_count
FROM images
LEFT JOIN views on views.image_id = images.image_id
GROUP BY images.image_id
ORDER BY view_count DESC

http://sqlfiddle.com/#!2/a669b/5

The GROUP BY clause tells the "aggregate functions" (count, sum, min, max, etc) how to behave. In this case, we are grouping by image and grabbing the count of views per image. COUNT only count non-null values, and we don't want to count the views that don't exist, so we're keying off views.view_id.

If you do an INNER JOIN rather than a LEFT JOIN, it will only return the images which have views. The LEFT JOIN allows us to get counts of zero.

于 2013-03-30T21:16:24.643 回答
0

You need to be looking at joins, join the images table to the images viewed table, then you can run one query across both tables.

于 2013-03-30T21:16:59.630 回答