dongyu8664 2014-01-07 00:05
浏览 8
已采纳

使用MySql JOINS在表中查找常用值

This is my way to check for mutual friends in my database.

For ex. if user one has friend user: (1, 2, 3, 4) and user two has friend user: (2, 4, 5) I want to show (2 and 4).

Is there any better way to do this using MYSQL JOINS for ex.?

I have a users table whith user_id column which contains all users id and friends table with user_one and user_two columns.

$user_one_fr = $db->query("select * from `friends` where `user_one` = '$session_user_id' or `user_two` = '$session_user_id'");
$user_two_fr = $db->query("select * from `friends` where `user_one` = '$user_id' or `user_two` = '$user_id'");

    while ($loop_user_one_fr = mysqli_fetch_assoc($user_one_fr)) {
        if($loop_user_one_fr["user_one"] == $session_user_id)
            $user_one_fr_array[] = $loop_user_one_fr["user_two"];
        else 
            $user_one_fr_array[] = $loop_user_one_fr["user_one"];
    }


    while ($loop_user_two_fr = mysqli_fetch_assoc($user_two_fr)) {
        if($loop_user_two_fr["user_one"] == $user_id)
            $user_two_fr_array[] = $loop_user_two_fr["user_two"];
        else 
            $user_two_fr_array[] = $loop_user_two_fr["user_one"];

    }

    $mutual_fr =  array_intersect($user_one_fr_array, $user_two_fr_array);

    foreach ($mutual_fr as $fr)
    echo $fr . ', ';
  • 写回答

1条回答 默认 最新

  • dounai6626 2014-01-07 01:41
    关注

    You can do it this way

    SELECT f1.friend mutual_friend
      FROM
    (
      SELECT IF(user_one = :user_id, user_two, user_one) friend
        FROM friends
       WHERE :user_id IN (user_one, user_two)
    ) f1 JOIN 
    (  SELECT IF(user_one = :session_user_id, user_two, user_one) friend
        FROM friends
       WHERE :session_user_id IN (user_one, user_two)
    ) f2 
        ON f1.friend = f2.friend;
    

    or

    SELECT IF(user_one IN(:user_id, :session_user_id), user_two, user_one) mutual_friend
      FROM friends
     WHERE :user_id IN (user_one, user_two)
        OR :session_user_id IN (user_one, user_two)
     GROUP BY IF(user_one IN(:user_id, :session_user_id), user_two, user_one)
    HAVING COUNT(*) > 1;
    

    Sample output (in both cases):

    | MUTUAL_FRIEND |
    |---------------|
    |             2 |
    |             4 |
    

    Here is SQLFiddle demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题