Skip to content
Advertisement

mysql count from table where related record exist in other table

I have 2 tables, customers and addresses. I want to count how many customers have addresses with name like a given search term

something like

SELECT COUNT(*) as countSearch FROM customers,addresses WHERE address.cu_id=customer.id AND customer.name like ?

Table Customers

 ________________
| id   |  name   |
 _________________
|  4   |  john   |
|  5   |  mark   |
 _________________

Table address


| id   |  cu_id   | address  |
 ____________________________
|  1   |  4       | ADRESS!! |
 _________________

Advertisement

Answer

You can use a inner join to connect both tables

This wouldm show how many addresses c.name has

SELECT COUNT(*) as countSearch 
FROM customers c INNER JOIN addresses a
     ON a.cu_id  = c.id
WHERE c.name like 'test'
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement