在我开发的消息传递应用程序中,我有一个用户表,其中包含基本帐户信息(名字,姓氏,用户名,加密密码等)和具有两列(前一个表的外键)的联系人表用户在他的联系人中有另一个。两个表都有一个标准的自动增量id列作为主键。
我有一个搜索栏,允许用户通过搜索关键字找到其他人,以便他们可以在他们的联系人中为他们添加书签。我可以使用此类查询获取此数据,$word
是搜索词,$id
是会话表中登录用户的ID:
select firstname
, lastname
, username
, id
from users
where (locate('$word', username) > 0
or locate('$word', firstname) > 0
or locate('$word', lastname) > 0)
and id <> '$id'
order
by username desc
limit 20
但是我发现用户必须知道他正在搜索的用户是否已经在他们的联系人中,所以我需要加入联系信息。我试过这个问题:
select users.firstname,
users.lastname,
users.username,
users.id,
contactsPrime.id as contact from users
left join
(select * from contacts as contactsPrime
where contacts.userID = '$id')
on users.id = contactsPrime.contactID
and (locate('$word', users.username) > 0
or locate('$word', users.firstname) > 0
or locate('$word', users.lastname) > 0)
order by username desc limit 20
我使用了别名表contactsPrime
,但我仍然遇到错误,我所有的派生表都没有别名。我哪里做错了?有没有更好的方法来达到我想要的效果?
答案 0 :(得分:1)
关于范围,contactsPrime
的范围()
并且无法在外部访问。
(select * from contacts as contactsPrime
where contacts.userID = '$id')
您将在行下方收到错误
on users.id = contactsPrime.contactID
您需要将其更改为
(select * from contacts where contacts.userID = '$id') as contactsPrime