简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM