[英]How to get result from two different table with one single input
I have two different tables with different column name 我有两个不同的列名称不同的表
Table 1 users 表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 |
+-----+----------+---------+---------+------------+
Table 2nd Company 表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 |
+-----+-------------+---------+---------=------+-----------+
Now whenever a user type any input in search bar an ajax request is made to php file which checks for if that name of user exist in database or not 现在,只要用户在搜索栏中输入任何输入,就会向php文件发出ajax请求,该文件检查数据库中是否存在该用户名
so for example if user type input john
then a query should run which will check john in users table and company table & if there is a user name john & if there is a company named john it should fetch both the result. 所以例如,如果用户输入john
那么应该运行一个查询,这将检查用户表和公司表中的john,如果有用户名john,如果有一个名为john的公司,它应该获取结果。
how can i achieve this, i tried using UNION in my query but it said columns are different 我怎么能实现这一点,我尝试在我的查询中使用UNION,但它说列是不同的
Currently this is my query 目前这是我的查询
$go = mysqli_query($connecDB, "SELECT name, img,username FROM users WHERE name LIKE '$q%' LIMIT 0,10");
Now people might be thinking what i really want! 现在人们可能会想到我真正想要的东西! i want a single query that will check for input in both table & fetch their details 我想要一个单一的查询,它将检查两个表中的输入并获取其详细信息
You can use union 你可以使用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.