Reputation: 2843
Im trying to count rows in a table. Currently im using this:
$sql = "SELECT COUNT(*)
FROM `friends`
WHERE `user1`='".$user1."'
AND `user2`='".$user2."'
AND `valid`=0
UNION
SELECT COUNT(*)
FROM `friends`
WHERE `user1`='".$user2."'
AND `user2`='".$user1."'
AND `valid`=0";
As you see, user1
can be both $user1
AND $user2
. but it does not count the rows after the UNION
, it only does the first query before UNION
so im ending up with 0 when i actually should be counting 1 row.
How do I solve this?
Upvotes: 1
Views: 153
Reputation: 23135
You can use an even simpler solution:
SELECT COUNT(*)
FROM friends
WHERE
$user1 IN (user1,user2) AND
$user2 IN (user1,user2) AND
valid = 0
Upvotes: 1
Reputation: 26766
Your query is actually returning 2 records - 0
for the first count and 1
for the second. You could use a sub-query to SUM()
your results...
$sql = "SELECT SUM(A) AS COUNT FROM
(SELECT COUNT(*) AS A
FROM `friends`
WHERE `user1`='".$user1."'
AND `user2`='".$user2."'
AND `valid`=0
UNION
SELECT COUNT(*)
FROM `friends`
WHERE `user1`='".$user2."'
AND `user2`='".$user1."'
AND `valid`=0
)";
Upvotes: 2
Reputation: 82933
Another alternative, replace your query with this:
$sql = "SELECT COUNT(*)
FROM `friends`
WHERE (
(`user1`='".$user1."' AND `user2`='".$user2."') OR
(`user1`='".$user2."' AND `user2`='".$user1."')
)
AND `valid`=0";
Upvotes: 4