在两个表中搜索并将结果与​​PDO组合

时间:2016-06-14 03:23:52

标签: php mysql

我有两个名为公司工作的表。它们是相关的 - 作业表有一个外键 company_id

公司表格列为:companyname,city,province等。

作业表格列:标题,部门,说明等

我想搜索这些列中的两个表格,如果关键字在作业表中匹配,请从公司表中获取相关数据,如果匹配是在公司表中,我想获得与公司相关的所有工作。

据我所知,为了在两个表中搜索,我必须使用UNION,这有效:

$sql= "(SELECT title, department FROM  jobs WHERE title LIKE ? ) 
UNION 
(SELECT companyname,city FROM  companies WHERE companyname LIKE ?)";

我不知道如何根据匹配从其他表中获取相关数据。是否可以使用JOIN进行一次调用?

感谢。

2 个答案:

答案 0 :(得分:1)

使用JOINOR条件:

SELECT jobs.title, jobs.department,
companies.companyname, companies.city
FROM jobs 
JOIN companies ON companies.id = jobs.company_id
WHERE (jobs.title LIKE ? OR companies.companyname LIKE ?)

使用UNION

SELECT jobs.title, jobs.department,
companies.companyname, companies.city
FROM jobs 
JOIN companies ON companies.id = jobs.company_id
WHERE jobs.title LIKE ?

UNION

SELECT jobs.title, jobs.department,
companies.companyname, companies.city
FROM jobs 
JOIN companies ON companies.id = jobs.company_id
WHERE companies.companyname LIKE ?

答案 1 :(得分:1)

试试这个

SELECT a.title, a.department,c.companyname, c.city
FROM a 
JOIN c ON c.id = a.company_id
WHERE (a.title LIKE 'title' OR c.companyname LIKE 'companyname')