开发者

How to join 2 tables based on a like in mysql

开发者 https://www.devze.com 2022-12-10 01:18 出处:网络
I have 2 tables Employee and Company_Employee. Employee: ID, FirstName Company_Employee: ID, Company_ID, Employee_I开发者_如何学CD

I have 2 tables Employee and Company_Employee.

Employee: ID, FirstName

Company_Employee: ID, Company_ID, Employee_I开发者_如何学CD

I want to do a search by First Name. I was thinking my query would look like:

   select FirstName, ID from Employee where FirstName LIKE '%John%' and ID in (select id from Company_Employee)

This query returns no rows. Does anyone know how I can get the rows with a like by FirstName with these 2 tables?

Thanks!


Your query compares a company_employee.id with an employee.id. It should probably compare employee.id with company_employee.employee_id.

You can rewrite the query more clearly with a join:

select *
from employee e
join company_employee ce
    on e.id = ce.Employee_ID
where e.FirstName like '%John%'


Something like this

SELECT
*
FROM
Employee e
INNER JOIN Company_Employee ce JOIN ON e.Id = ce.Id)
WHERE 
FirstName LIKE '%JOHN%'
0

精彩评论

暂无评论...
验证码 换一张
取 消