首先根据条件对所选ID进行排序的SQL语句

时间:2012-04-02 18:50:29

标签: mysql sql

我有以下表格:

team_members

userid
teamid

用户

uid
name_f
name_l

朋友

friend_id
friend_one
friend_two

我使用以下语句来选择属于某个团队的用户的uid和profile_pic。

SELECT DISTINCT u.uid, u.profile_pic
FROM friends f, users u, team_members m
WHERE m.teamid =$team_var
AND u.uid = m.userid

我还必须运行以下内容来选择用户的用户的属于某个团队。< / p>

SELECT DISTINCT u.uid, u.profile_pic
FROM friends f, users u, team_members m
WHERE m.teamid =$team_var
AND u.uid = m.userid
AND m.userid = f.friend_two
AND f.friend_one =$session_id

我正在寻找一种方法来加入这两个,而不是运行2个查询,运行一个可以订购的单个查询,并列出与顶部登录用户成为朋友的用户。因此,假设某个团队有30个用户,其中5个用户是登录用户的朋友,我希望在声明之后的while循环中列出的前5个用户是剩下的25随机显示。

感谢您的时间。

3 个答案:

答案 0 :(得分:1)

使用外连接可以很容易地解决这个问题。如果没有显式连接语法,您可能无法使用外连接。这里:

SELECT
  u.uid,
  u.profile_pic,
  (friend_id IS NOT NULL) AS is_friend
FROM team_members m
  INNER JOIN users u ON m.userid = u.uid
  LEFT JOIN friends f ON m.userid = f.friend_two AND f.friend_one = $session_id
WHERE m.teamid = $team_var
ORDER BY
  is_friend DESC,
  m.userid

前两个表使用内部联接进行连接,因此只返回特定团队的成员(因为我们正在teamid上进行过滤)。

friends表外连接到上一个连接的结果。更具体地说,我们加入friends子集,其中friend_one是当前用户。返回前一个结果集中的所有行,但返回匹配的friends子集中的行。如果不匹配,则friends列会填充NULL s。

使用NULL(或更确切地说NOT NULL)测试,我们可以看到哪个团队成员是朋友,哪个不是。测试结果作为列返回,并且还用作输出行的排序标准。

答案 1 :(得分:0)

您需要创建另一个列,其值为“friend”或不是“friend”。然后,您将该列用作ORDER BY。您创建的列可以是子查询,以确定其他用户是否是朋友。以下代码是错误的,因为您需要将外部查询中的数据挂钩到子查询中,但它应该类似于:

SELECT DISTINCT u.uid, u.profile_pic,
EXISTS (SELECT DISTINCT u.uid, u.profile_pic 
FROM friends f, users u, team_members m 
WHERE m.teamid =$team_var 
AND u.uid = m.userid 
AND m.userid = f.friend_two 
AND f.friend_one =$session_id 
) AS myColumn 
FROM friends f, users u, team_members m 
WHERE m.teamid =$team_var 
AND u.uid = m.userid 
ORDER BY myColumn

答案 2 :(得分:0)

我可能会建议:

select u.uid, u.profile_pic
from team_members t
    join team_members m on t.teamid = m.teamid
    join users u on m.userid = u.uid
    left join friends f on t.userid = f.friend_one and m.userid = f.friend_two
where m.userid != t.userid
    and t.userid = $session_id -- This line can be removed to view all (test)
order by
    --t.teamid, t.userid, -- This line can be added to order all (test)
    (case when f.friend_id is null then 1 else 0 end case),
    f.friend_id, m.userid

我正在使用显式连接语法(通常建议这些天使用)并按顺序使用该case语句将朋友带到顶部。我没有在这里运行MySQL来测试它,但语法应该非常标准(我在SQL Server上运行的东西非常相似)。