是否可以一次查询3件事?

时间:2011-12-29 03:06:35

标签: php mysql

我正在为我的新页面添加一个5星投票系统。我有以下4个表:id,sid,rating,ipaddress。

我正在尝试(在我的查询中)计算新闻条目的平均投票数,计算总票数+检查以查看该IP地址是否已经对此新闻项目进行投票。

这就是我已经处理的投票平均值/投票数:

$result = mysql_query("SELECT AVG(rating) AS ave_rating, count(*) AS votes FROM news_ratings WHERE sid = $sid GROUP BY sid");
$obj = mysql_fetch_object($result);
$rating = $obj->ave_rating;
$votes = $obj->votes;

是否可以修改它以检查“ipaddress”表以查看是否匹配?

1 个答案:

答案 0 :(得分:1)

我认为你的意思是你有4个,而不是表格......

您只需要在AND子句中添加逻辑WHERE

SELECT 
  AVG(rating) AS ave_rating,
  count(*) AS votes 
FROM news_ratings
WHERE
  sid = $sid
  AND ipaddress = '$ipaddress'
GROUP BY sid

更新

在评论之后,要返回具有相同查询的IP匹配,您可以使用CASE语句在ipmatch列表中创建名为SELECT的列:

SELECT 
  AVG(rating) AS ave_rating,
  count(*) AS votes, 
  CASE WHEN ipaddress = '$ipaddress' THEN 'IP-MATCH' ELSE 'IP-NOMATCH' END AS ipmatch
FROM news_ratings
WHERE
  sid = $sid
GROUP BY sid