I have a database which holds information about user-created items. Each item can have a number of images associated with it, and I’d like to have an SQL query that 4 random item images, but should not return images from the same item twice.
Here’s a review of the table structures (not full, but including the pertinent information):
Table 1 : item_images:
+----------+--------------+
| item_id | filename |
+----------+--------------+
| 1 | test.jpg |
| 1 | test2.jpg |
| 5 | testy.jpg |
+----------+--------------+
Table 2: item_link:
+----------+-------------+
| item_id | category_id |
+----------+-------------+
| 1 | 1 |
| 5 | 1 |
+----------+-------------+
So given the above data, I’d like to return a random image for item # 1 and 5, since they both exist in category # 1.
Here’s the SQL query I have already tried, but for some reason, it always returns the same two images. How might I modify this to return a random image from the matched items?
SELECT `item_images`.`filename` AS `url` FROM `item_images`
INNER JOIN `item_link` ON `item_images`.`item_id` = `item_link`.`item_id`
WHERE `item_link`.`category_id` = 1
GROUP BY `item_link`.`item_id`
ORDER BY RAND()
LIMIT 4
webduos is right distinct should solve your problem
here is explaination