Dave
Dave

Reputation: 307

Is it possible to query for 3 things at once?

I'm adding a 5 star voting system to my new page. I have the following 4 tables : id, sid, rating, ipaddress.

What I'm trying to do (in my query) is calculate the average vote for a news entry, count how many total votes there are + check to see if the ip address has already voted on this news item.

This is what I have already to handle the vote average / vote count :

$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;

Can this be modified to also check the "ipaddress" table to see if there is a match?

Upvotes: 2

Views: 72

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270637

I think you mean you have 4 columns, rather than tables...

You just need to add a logical AND to your WHERE clause:

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

Update

After comments, to return an IP match with the same query, you can use a CASE statement to create a column called ipmatch in your SELECT list:

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

Upvotes: 1

Related Questions