简体   繁体   English

MySQL选择不重复并确定是否只有一个user_id

[英]MySQL select distinct and determine if only one user_id exists

I would like to run a query to show if there is one or more than one user_id for given poll_id. 我想运行一个查询,以显示给定的poll_id是否有一个或多个user_id。

Example 1: poll_id 1106 has only user_id 1 for all it's rows. 示例1:poll_id 1106的所有行都只有user_id 1。

Example 2: poll_id 1106 has more than one user_id 1 for all it's rows. 示例2:poll_id 1106的所有行都具有多个user_id 1。

两个例子图片

Using the example given below, this php code works: 使用下面给出的示例,此php代码有效:

$sql = "
SELECT 1 
FROM xf_poll_vote
WHERE poll_id='1106'
having count(distinct user_id) > 1";

// execute SQL query and get result 
$sql_result = mysql_query($sql,$connection); 

// format results by row 
while ($row = mysql_fetch_array($sql_result)) { 

    $user_id[] = $row["user_id"];

}

$count = count($user_id);

echo $count;

Just a COUNT / DISTINCT I think. 我认为只有COUNT / DISTINCT。

SELECT poll_id, CASE WHEN COUNT(DISTINCT user_id) > 1 THEN 'Many' ELSE 'One' END AS ManyOrOne
FROM SomeTable
GROUP BY poll_id
select 1
from yourTable
where poll_id = @yourPoll_id
having count(distinct user_id) > 1

if returns you anything, that poll_id have more than one user. 如果返回任何内容,则该poll_id具有多个用户。 If not, only have one or zero users 如果没有,则只有一个或零个用户

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

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