homepage Welcome to WebmasterWorld Guest from 54.211.219.68
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / Databases
Forum Library, Charter, Moderator: open

Databases Forum

    
Using Rand to return 2 results
mysql rand query
jspeed

5+ Year Member



 
Msg#: 4185452 posted 4:48 pm on Aug 11, 2010 (gmt 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!

 

redhatlab

5+ Year Member



 
Msg#: 4185452 posted 9:56 pm on Aug 11, 2010 (gmt 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.

redhatlab

5+ Year Member



 
Msg#: 4185452 posted 10:00 pm on Aug 11, 2010 (gmt 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.

jspeed

5+ Year Member



 
Msg#: 4185452 posted 1:09 am on Aug 15, 2010 (gmt 0)

Thank you for the tips, I appreciate it!

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / Databases
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved