I have this table:
id | id_user | id_user_stalkers | date
0 | 0222222 | 032332 | 32234234
so, i want to know count of all users that are in my friends list, and cout of all users that have me in their friend list.
at the moment, i’ve made this query :
SELECT (
SELECT COUNT(id_user)
FROM stalkers WHERE id_user = ".$id."
) AS user_stalkers,
(
SELECT COUNT(id_user_stalkers)
FROM stalkers WHERE id_user_stalkers = ".$id."
) AS user_is_stalked
FROM stalkers
but it returns this:
Array
(
[0] => Array
(
[user_stalkers] => 7
[user_is_stalked] => 2
)
[1] => Array
(
[user_stalkers] => 7
[user_is_stalked] => 2
)
[2] => Array
(
[user_stalkers] => 7
[user_is_stalked] => 2
)
[3] => Array
(
[user_stalkers] => 7
[user_is_stalked] => 2
))
it’s all right, but i need only one row, not four.
Can somebody help me please ?
Since all your fields are subqueries you can drop the from clause altogether. Otherwise you get a subquery for every single row in the table. This not only gets the results you want but reduces total hit on the database by a potentially very large amount (increasing performance).
If this is going to be a potentially large table you’ll want to make sure id_user and id_user_stalkers are both indexed. If an index can be used these sub-queries will be much much faster.