简体   繁体   English

选择然后再选择不同的值

[英]select and then again select distinct values

I have 3 columns questionid , replyid and userid . 我有3列questionidreplyiduserid

I want to select all questionid's from userid where userid is session[userid] , And then select distinct questionid from it. 我想questionid's from userid where userid is session[userid]选择所有questionid's from userid where userid is session[userid] ,然后从中选择不同的questionid

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 现在我把所有那些属于$_SESSION['user_id'] questionid放在一个数组中(并从中删除重复项)然后我再次传递另一个查询

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... 但由于8,28,3在同一个网页(一个问题和两个答案),我想避免显示重复的问题...

So I was trying the wrong way as I was taking distinct questionid and then again selecting * from table where questionid was previous one. 所以我正在尝试错误的方式,因为我采取了明显的questionid ,然后再次* from table where questionid选择* from table where questionid是前一个。

But then as @ Mahmoud Gamal suggested I did 但是,正如@ Mahmoud Gamal建议的那样

 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 所以我加了limit 0,1

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

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 . 这将为您提供DISTINCT questionid, replyid, userid But this isn't by necessary, contains DISTINCT(questionid) . 但这不是必要的,包含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 . 如果您正在寻找distinct questionid ,那么最终会得到一个GROUP BY questionid其中包含其他两个字段replyid, userid ,如SUMMAXMIN聚合函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM