views:

25

answers:

3

I have these two tables:

tAccounts
id, name, server_id

tFriends
id_lo, id_hi

Now, I'm trying this query:

SELECT FR.id_lo AS id_friend
FROM tFriends FR, tAccounts AC
WHERE (FR.id_hi = 4 && AC.server_id != -1)

........ In order get the friends of a certain user, while making sure his friend's server_id is different than '-1' !

Any idea? It seems like the 'AC.server_id != -1' constraint in the WHERE clause doesn't give me the expected results.

+2  A: 

Where is you join condition ? It should be something like this: (I assume that tFriends.id_lo is an account id of friend)

SELECT FR.id_lo AS id_friend
FROM tFriends FR 
INNER JOIN tAccounts AC ON (AC.id = FR.id_lo AND AC.server_id != -1)
WHERE FR.id_hi = 4 ;
a1ex07
+2  A: 

You need to join the two tables; otherwise, you get a Cartesian product (combining all rows of tFriends where id_hi = 4 with all rows of tAccounts where server_id is not -1).

Try this:

SELECT FR.id_lo AS id_friend
FROM tFriends FR
INNER JOIN tAccounts AC ON AC.id = FR.id_hi
WHERE (FR.id_hi = 4 && AC.server_id != -1)
I wasn't sure which of id_lo and id_hi to join on, so I just picked one.
+1  A: 

Try joining the account table twice:

SELECT *
FROM tAccounts a1
JOIN tFriends f ON a1.id = f.id_lo
JOIN tAccounts a2 ON a2.id = f.id_hi
WHERE a1.id = 4 AND a2.server_id != -1
   OR a2.id = 4 AND a1.server_id != -1

Or use a UNION:

SELECT *
FROM tAccounts a
JOIN tFriends f ON a.id = f.id_lo
WHERE f.id_hi = 4 AND a.server_id != -1
UNION
SELECT *
FROM tAccounts a
JOIN tFriends f ON a.id = f.id_hi
WHERE f.id_lo = 4 AND a.server_id != -1
Mark Byers
Thanks Mark, so yours is the only one I needed. A question; How is it in performance terms? I might have 4-5 million friendship row and a few hundred thousands accounts. Besides adding a memcached boxes, if we're talking only about the sql statement; How can I achieve better performance? Will having the 'server_id' field on the 'tFriends' table will save a lot of CPU, because it'll avoid a JOIN of the two tables?
Poni
@Poni: You would need to add server_id_lo and server_id_hi. That would improve performance. The best way to get good performance is to measure it for a variety of different queries / indexing strategies and see what works best.
Mark Byers
Thank you ! ........
Poni