dpiuqwwyu187975836 2016-06-14 03:23
浏览 29
已采纳

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

I have two tables named companies and jobs. They are related - jobs table has a foreign key company_id.

company table columns are: companyname, city, province etc.

jobs table columns: title, department, description etc

I want to search both tables in those columns and if the keyword has a match in jobs table get the related data from the company table, and if the match is in the company table, I want to get all the jobs related to the company.

As far as I know in order to search in both tables I have to use UNION, this works:

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

I dont know how to get related data from the other table depending on the match. Is it possible with just one call using JOIN?

Thanks.

  • 写回答

2条回答 默认 最新

  • 普通网友 2016-06-14 04:08
    关注

    Use JOIN and OR condition:

    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 ?)
    

    With 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条)

报告相同问题?

悬赏问题

  • ¥15 html5+css有人可以帮吗?
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?