mysql仅在另一行的字段等于时才选择行

时间:2010-09-01 19:59:16

标签: mysql select where-clause

我有这两个表:

tAccounts
id,name,server_id

tFriends
id_lo,id_hi

现在,我正在尝试此查询:

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

........为了获得某个用户的朋友,同时确保他朋友的server_id与'-1'不同

有什么想法吗?看起来WHERE子句中的'AC.server_id!= -1'约束不能给出预期的结果。

3 个答案:

答案 0 :(得分:2)

你在哪里加入条件?它应该是这样的:(我假设tFriends.id_lo是朋友的帐号)

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 ;

答案 1 :(得分:2)

你需要加入这两个表;否则,你得到一个笛卡儿积(将id_hi = 4的所有行与所有tAccounts行组合,其中server_id不是-1)。

试试这个:

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)

答案 2 :(得分:1)

尝试加入帐户表两次:

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

或使用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