php - 将两个查询合并在一起

标签 php mysql

好的,我的网站使用 Facebook Api,它将导入将要登录的用户的所有好友(用户 ID、名称),因此我的表结构如下:

users: id, name
usersFriends: id, friendUserId, name

所以当用户加入网站时,他们会得到所有的 friend 导入,示例数据:

user: 237374734 (facebook user id), John brouwers (name of the user)

然后它将导入 John 的所有 friend 。例如:

userFriends: 237374734 (John user id), 2737373, Michael jackson

现在我需要的是一个将通过 friend 搜索(按名称)的查询,即 加入没问题,但我需要的是在查询中我需要检查用户是否在我的网站上所以让我们举个例子:

我们用用户 John 登录,我们正在搜索 michael 这样就可以了

SELECT name FROM userFriends WHERE name LIKE %michael%

但我需要的不仅仅是返回用户名,我还需要检查用户是否存在于用户表中。

抱歉说来话长,希望我的问题很清楚。已经谢谢了!

最佳答案

编辑:所以你需要一个查询,通过姓名搜索 friend ,并检查用户表中是否存在 friend ,如下所示:

create table Users(
   Id int not null,
   primary key (Id),
   Name varchar(50) not null
)TYPE=MyISAM;
create table UserFriends(
   Id int not null,
   foreign key (Id) references Users(Id),
   FriendUserId int not null,
   Name varchar(50) not null
)Type=MyISAM;
insert into Users(Id,Name) values(237374734,'John brouwers');
insert into UserFriends(Id,FriendUserId,Name)
values(237374734, 2737373, 'Michael jackson');

下面的查询将搜索他的名字如“%Michael%” 的用户并检查他是否是注册用户:

select s.Id, s.Name, 
       case when exists 
       ( 
           select Name from users where Name like "%Michael%" 
       ) Then 'Registered User'
       else
       (
           'Not Registered'
       )
       end
       as 'Is Registered in My Website'
from 
(
      select uf.FriendUserId Id, uf.Name
      from UserFriends uf
      left join users u on u.Id = uf.friendUserId
      where uf.name like "%Michael%"
) s

这会给你:

Id              Name        Is Registered in My Website
2737373   Michael jackson        Not Registered

希望这会有所帮助,如果有任何问题,请不要犹豫。

关于php - 将两个查询合并在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8285320/

相关文章:

java - 如何管理 Apache Web 服务器和 Google App Engine 之间的 HTTP 通信?

Mysql根据列输入动态更新行

mysql - 在数据库中设计用户/角色/人员的最佳实践

c# - 当datacolumn[row][0]返回system.byte时如何查看字符串

javascript - 向 Google 折线图添加多条线

php - 如何将mysql表数据写入excel文件但不下载只存储文件

javascript - php登录后如何将用户重定向到特定链接

mysql - 如何锁定一个mysql数据库中的所有表?

java - 如何减少部分冲洗

php - 检查 Cookie 是否存在于 CodeIgniter 中