douzinei6926 2014-04-29 22:57
浏览 27
已采纳

遵循mySQL表搜索结果

I have a following system where users can follow each other and search for users to follow. Here are examples of the users and following tables:

Users Table:
+-------+-----------+
| id    | userName  |
+-------+-----------+
| 1     | John      |
| 2     | Harriet   |
| 3     | Chris     | 
| 4     | Lisa      | 
| 5     | Joe       | 
+-------+-----------+

Following Table:
+-------+-------+-------+
| id    | id_1  | id_2  |
+-------+-------+-------+
| 1     | 5     | 3     |
| 2     | 1     | 2     |
| 3     | 1     | 5     |
| 4     | 5     | 4     |
+-------+-------+-------+

I want to know how to structure a mySQL statement to join the following table with the users table where the username is like '%$search%' to return all results of this occurrence (i.e. searching 'jo' returns John and Joe) and when there are multiple results for each person (i.e. Joe will occur twice in Following) return only results where id_1 is the current logged in users id to show that the logged in user is already following this person.

$search = $_POST['search'];
$userid = $_POST['userid'];

$qry = "
SELECT u.id
     , u.userName
     , f.id_1
     , f.id_2 
  FROM users u
  LEFT 
  JOIN following f
    ON IF('$userid' = f.id_1, u.id = f.id_2, u.id = f.id_1)
 WHERE u.userName LIKE '%$search%';
 ";

This query returns every occurrence of the username in the following table but it should only return once.

Any help would be great. Thanks.

  • 写回答

1条回答 默认 最新

  • douju6752 2014-04-29 23:11
    关注

    Not absolutely sure but give it a try

    SELECT u.id
         , u.userName
         , f.id_1
         , f.id_2 
      FROM users u
      LEFT JOIN following f
      ON u.id in (f.id_1,f.id_2)
      AND f.id_1 = '$userid'
     WHERE u.userName LIKE '%$search%'
     ORDER BY u.id
     LIMIT 1;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器