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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18570021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:43:08  来源:igfitidea点击:

Select id from one table and its value from another table to search

mysqlselectwheresql-like

提问by Montiyago

I have two tables named companyand customers.

我有两个名为company和 的表customers

In companytable there are 3 fields ID, Company, and Typeas:

company表中有3个字段IDCompany以及Type为:

ID    Company    Type
1     ABC        Running

2     XYZ        Current

Now again in customerstable I submitted the value of company and customers, but here the value of company is submitted as an IDas:

现在再次在customers表中提交公司和客户的价值,但这里公司的价值提交ID为:

Company     Customer Name
1              monty

2             sandeep

now I want to search the company name in customer table but when i put company name in search box its showing nothing because the value of company name is in ID form in customer tabe.how can i achieve it.

现在我想在客户表中搜索公司名称,但是当我将公司名称放入搜索框中时,它什么也不显示,因为公司名称的值是客户表中的 ID 形式。我该如何实现。

Here is my query for search:

这是我的搜索查询:

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

回答by Mahmoud Gamal

By JOINing the two tables:

通过JOINing 两个表:

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%'

回答by Ankur Dhanuka

try this

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