Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select and then again select distinct values

I have 3 columns questionid, replyid and userid.

I want to select all questionid's from userid where userid is session[userid], And then select distinct questionid from it.

Right now I take all those questionid belonging to $_SESSION['user_id'] in an array( and remove duplicates from it) and then I again pass another query

foreach($array as $x)
{
$query="select questionid,replyid,userid from table where questionid=$x"
}

But I think that the above steps can be done in query itself(and the above step is not working also). I tried below but its not working. If I try to pass this query then duplicate value still comes:

SELECT distinct(questionid),replyid,userid 
from table 
where userid=$_SESSION['user_id']

So what should be the query?

questionid,replyid,userid

8          ,2     ,45

8          ,3      ,45

9           ,8      ,41

But as 8,2 and 8,3 are in same webpage(one question and two answers), I want to avoid showing duplicate question...

So I was trying the wrong way as I was taking distinct questionid and then again selecting * from table where questionid was previous one.

But then as @ Mahmoud Gamal suggested I did

 SELECT distinct questionid, `answerid`, `userid`
 FROM `table` 
 WHERE  userid='$user' 

But again I had done the same duplicate thing. So I added limit 0,1

 SELECT distinct questionid, `answerid`, `userid`
 FROM `table`
 WHERE  userid='$user' 
 LIMIT 0,1
like image 850
netuser Avatar asked Nov 13 '22 21:11

netuser


1 Answers

This is the equivalent of the two queries you described in your post:

SELECT DISTINCT questionid, replyid, userid 
FROM table 
WHERE questionid IN
(
    SELECT DISTINCT questionid
    FROM table 
    WHERE userid = @user_id
)

This will give you DISTINCT questionid, replyid, userid. But this isn't by necessary, contains DISTINCT(questionid).

If you are looking for distinct questionid, you will end up with a GROUP BY questionid with aggregate functions for other two fields replyid, userid, like SUM, MAX or MIN.

like image 52
Mahmoud Gamal Avatar answered Nov 15 '22 11:11

Mahmoud Gamal