从一个表中选择id,从另一个表中选择其值进行搜索

时间:2013-09-02 09:40:05

标签: mysql select where sql-like

我有两个名为companycustomers的表。

company表中,有3个字段IDCompanyType为:

ID    Company    Type
1     ABC        Running

2     XYZ        Current

现在再次在customers表中我提交了公司和客户的价值,但此处公司的价值以ID提交为:

Company     Customer Name
1              monty

2             sandeep

现在我想在客户表中搜索公司名称,但是当我在搜索框中输入公司名称时,它显示什么,因为公司名称的值在客户tabe中以ID形式显示。我可以实现它。

以下是我对搜索的查询:

$sql = "Select * from customers where name like '%$term%' or location like '%$term%' or company like '%$term%'";

2 个答案:

答案 0 :(得分:12)

通过JOIN两个表:

Select * 
from customers AS cust
INNER JOIN companies AS comp ON cust.Company = comp.Id
where comp.location like '%$term%' 
   or comp.company like '%$term%'

答案 1 :(得分:4)

try this

SELECT co.*, cu.* FROM company as co, customers as cu where co.company_id = cu.company_id and co.company_name = '%$term%';