开发者

mysql select a row only if a field at another row is equal to

开发者 https://www.devze.com 2023-01-14 23:35 出处:网络
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

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 maki开发者_如何学编程ng 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.


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 ;


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)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消