所以,在我遇到这个想法之前,我认为我已经相当擅长MySQL了:
我有一个表格记录“投票”(恰当地命名为votes
)这些字段:
id
:投票的唯一ID。user
:投票人的唯一用户ID item
:他们投票的项目ID vote
:他们投票的投票('上','下')现在,我正在尝试用SQL方法来查找只有投票结果的用户。我知道在从表中查询大部分数据后在php中以程序方式编写它的方法,但是当只有少数查询可以找到它时,这样做真的非常非常低效。
理想情况下,我希望我的结果只是一个有0个赞成票的用户列表(因为在表中表示他们已经投票,所以他们只是投票),也许他们投下的票数。
关于我应该如何处理的任何想法?
答案 0 :(得分:5)
SELECT user, SUM(IF(vote='down',1,0)) AS numDownVotes
FROM votes
GROUP BY user
HAVING SUM(IF(vote='up',1,0))=0 -- 0 upvotes
AND SUM(IF(vote='down',1,0))>0 -- at least 1 downvotes
我不禁感到有一种干净的GROUP BY user, vote
方式来做到这一点。
答案 1 :(得分:3)
select user, count(user)
from votes
where user not in (
select distinct user
from votes
where votes = 'up')
答案 2 :(得分:3)
我没有检查语法或任何内容,但我想到了......
SELECT user
FROM votes
GROUP BY user
HAVING SUM(IF(vote = 'up', 1, 0)) = 0
AND SUM(IF(vote = 'down', 1, 0)) > 0
答案 3 :(得分:1)
select v.user from votes v where
0=(select count(a.vote) from votes a where a.user=v.user and a.vote='up' group by user) u
and
0 <(select count(a.vote) from votes a where a.user=v.user and a.vote='down' group by user) d
group by user;
答案 4 :(得分:0)
在数据库调用上执行此操作有什么问题吗?类似的东西:
$query = "SELECT id FROM votes WHERE vote = 'down'";
$result = mysql_query($query);
while ($rows = mysql_fetch_assoc($result))
{
$curID = $rows['id'];
}
答案 5 :(得分:0)
<?php
// Make a MySQL Connection
$query = "SELECT user, COUNT(user) FROM votes where vote == 'down' GROUP BY user";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "User : ". $row['type'] ." has ". $row['COUNT(user)'] ." downvote/s.";
echo "<br />";
}
?>