我有一个带有这些属性的表(BUDDY)
如果status ='a'表示请求者和请求者是好友 但是,如果用户可以是请求者和请求者,我怎么能知道某个用户的好友呢?
SELECT requestor, requested
FROM buddy,user
WHERE user_id = requestor or user_id = requested
这给了我多个价值观?
答案 0 :(得分:2)
如果您想从用户那里获取某些字段,则需要将buddy
加入user
表。否则,您将获得不相关的交叉连接。
但是,看起来您不需要任何用户的列,因此下面的简单更改应该可以解决这个问题:
SELECT requestor, requested
FROM buddy
WHERE user_id = requestor or user_id = requested
如果要添加用户的字段,请添加联接:
SELECT b.requestor, b.requested, u.first_name, u.last_name
FROM buddy b
JOIN user u ON b.requestor=u.id OR b.requested=u.id
WHERE user_id = b.requestor or user_id = b.requested
答案 1 :(得分:0)
给定用户U
SELECT requestor
FROM buddy
WHERE requested = U AND status='a'
UNION
SELECT requested
FROM buddy
WHERE requestor = U AND status='a'
答案 2 :(得分:0)
以下内容如何:
SELECT b.requested AS MyBuddy
FROM buddy AS b
INNER JOIN user AS u1 u1.user_id = b.requestor
WHERE buddy.status = 'a'
AND u1.user_id = 101
UNION
SELECT b.requestor AS MyBuddy
FROM buddy AS b
INNER JOIN user AS u2 u2.user_id = b.requested
WHERE buddy.status = 'a'
AND u2.user_id = 101
第一个查询会在requestor
中搜索有问题的用户,如果状态为a
,则会将requested
作为MyBuddy
。第二个查询会在requested
中搜索相关用户,如果状态为a
,则会将requested
作为MyBuddy
。然后将两个查询联合起来以获得完整列表。
我加入了user
表格,因为您可能希望在SELECT中使用u1.name
而不是b.requested
和b.requestor
。
答案 3 :(得分:0)
只需加入user
这两个条件:
SELECT requestor, requested, u.user_name AS Buddy
FROM buddy b
INNER JOIN user u
ON (@userID = requestor AND b.requested = u.user_id)
OR (@userID = requested AND b.requestor = u.user_id)
WHERE status = 'a'