繁体   English   中英

如何通过一个输入从两个不同的表中获得结果

[英]How to get result from two different table with one single input

我有两个不同的列名称不同的表

表1用户

+-----+----------+---------+---------+------------+
|  id |   name   | username| image   |   email    |
+-----+----------+---------+---------+------------+
|  1  |  John1   | exmple1 |  img1   |a@gmail.com |
|  2  |  John2   | exmple2 |  img2   |b@gmail.com |
|  3  |  John3   | exmple3 |  img3   |c@gmail.com |
|  4  |  John4   | exmple4 |  img4   |d@gmail.com |
+-----+----------+---------+---------+------------+

表2公司

+-----+----------+------------+---------=------+-----------+
|  id |company_name | username|  description   |   founded |
+-----+-------------+---------+----------------+-----------|
|  1  |    john1    | exmple1 |description1    |    2016   |
|  2  |CompanyName2 | exmple2 |description2    |    2016   |
|  3  |CompanyName3 | exmple3 |description3    |    2016   |
|  4  |CompanyName4 | exmple4 |description4    |    2016   |
+-----+-------------+---------+---------=------+-----------+

现在,只要用户在搜索栏中输入任何输入,就会向php文件发出ajax请求,该文件检查数据库中是否存在该用户名

所以例如,如果用户输入john那么应该运行一个查询,这将检查用户表和公司表中的john,如果有用户名john,如果有一个名为john的公司,它应该获取结果。

我怎么能实现这一点,我尝试在我的查询中使用UNION,但它说列是不同的

目前这是我的查询

$go = mysqli_query($connecDB, "SELECT name, img,username FROM users WHERE name LIKE '$q%' LIMIT 0,10");

现在人们可能会想到我真正想要的东西! 我想要一个单一的查询,它将检查两个表中的输入并获取其详细信息

你可以使用union

select  id,  name  ,username, image, email, null, null
from users
where name LIKE concat('$q', '%')
union all
select  id,  company_name as name  ,username, null, null, description, founded 
from Company 
where name LIKE concat('$q, '%')
order by name limit 10

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM