Jump to content

Recommended Posts

Okay, instead of bumping my topic from yesterday, I'm going to post a new one.. maybe it was confusing. :shrug: Below is my query right now.

 

mysql_query("
SELECT *
FROM posts
JOIN forums ON ( forums.forum_id = posts.forum_id )
JOIN users ON ( users.user_id = posts.poster_id )
ORDER BY post_time DESC
LIMIT 4
");

 

I need to grab 4 rows from my database. These 4 rows have to have a unique value for posts.topic_id. I can probably figure out some loops and do it someway like that, but if I could get it in the query that would be great.

Thanks

Link to comment
https://forums.phpfreaks.com/topic/193063-unique-value-in-column/
Share on other sites

SELECT DISTINCT posts.post_id
FROM posts
JOIN forums ON ( forums.forum_id = posts.forum_id )
JOIN users ON ( users.user_id = posts.poster_id )
ORDER BY post_time DESC
LIMIT 4

 

And if you want the whole record (although this might be a performance hit):

SELECT * FROM posts WHERE post_id IN (
SELECT DISTINCT posts.post_id
FROM posts
JOIN forums ON ( forums.forum_id = posts.forum_id )
JOIN users ON ( users.user_id = posts.poster_id )
LIMIT 4)
ORDER BY post_time DESC

 

On the second one:

#1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

 

I am needing to pull all of the information, or if not all.. there is a quite a bit I will have to type out to get all I need. Either way, I think IN isn't supported.

 

 

Also, it's topic_id not post_id.. not a big deal though I can just change that :P

Ok, how about

SELECT * FROM posts WHERE topic_id IN (
SELECT DISTINCT posts.topic_id
FROM posts
JOIN forums ON ( forums.forum_id = posts.forum_id )
JOIN users ON ( users.user_id = posts.poster_id )
ORDER BY post_time DESC 
)
LIMIT 4

 

Just remember that the subquery might be a performance hit because you're scanning and retrieving all of the records.  It would probably be better to just run the non-subquery version (the first answer), then loop through each topic_id in code and select each record, since you'll only need to query for 4 records.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.