Welcome to WebmasterWorld Guest from 54.159.129.152

Forum Moderators: open

Message Too Old, No Replies

Using Rand to return 2 results

mysql rand query

     
4:48 pm on Aug 11, 2010 (gmt 0)

Junior Member

5+ Year Member

joined:Dec 13, 2007
posts:72
votes: 0


I have the following query that im using to return 2 random values.

I want to be able to return two (2) random unique values. Here is the query:

SELECT projects.id, projects.title, projects.description, projects.catid, projectimages.image, projectimages.projectid
FROM projects
INNER JOIN projectimages
ON projects.id = projectimages.projectid
WHERE featured = 'yes' ORDER BY Rand() LIMIT 2

It works correctly - but problem is - the table is not that big, and sometimes it returns two of the same value. So its lists 1 project twice.

Any help/pointers are appreciated!
9:56 pm on Aug 11, 2010 (gmt 0)

Junior Member

5+ Year Member

joined:Dec 29, 2008
posts: 65
votes: 0


Hi,

You can use DISTINCT or GROUP BY to avoid duplicate records. Also make sure you are joining the tables using proper index, because the day the tables are big the query is going to take longer.
10:00 pm on Aug 11, 2010 (gmt 0)

Junior Member

5+ Year Member

joined:Dec 29, 2008
posts: 65
votes: 0


Also (I click submit to quickly) if you are making a 1 to many join on the SQL you might want to use LEFT JOIN or RIGHT JOIN instead.

One more thing if projects.id is the same as projectimages.projectid you don't need to ask for it again. And in the WHERE you should do projectimages.featured instead of just featured.
1:09 am on Aug 15, 2010 (gmt 0)

Junior Member

5+ Year Member

joined:Dec 13, 2007
posts:72
votes: 0


Thank you for the tips, I appreciate it!
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members