选择与另外两个表具有多个连接的行

时间:2014-01-30 12:39:01

标签: mysql

假设我有三张桌子:

table `customers` with columns `id`,`name`
table `contracts` with columns `id`, `customer_id`, `text`
table `phones` with columns `id`, customer_id`, `number`

我想选择拥有超过1份合约和多个电话号码的客户。我试着做下面的事情:

SELECT * FROM `customers` 

WHERE 

 (SELECT count(*) FROM `contracts` WHERE `customer_id` = `id`) > 1 
  AND 
 (SELECT count(*) FROM `phones` WHERE `customer_id` = `id`) > 1

但它会产生错误#1054 - Unknown column 'customer_id' in 'where clause'

2 个答案:

答案 0 :(得分:2)

请尝试以下查询:

SELECT customers.* FROM customers

INNER JOIN
(

  SELECT customer_id, count(*) AS count FROM contracts GROUP BY customer_id 

  HAVING count > 1

) AS contracts

ON customers.id = contracts.customer_id

INNER JOIN

(

  SELECT customer_id, count(*) AS count FROM phones GROUP BY customer_id 

  HAVING count > 1

) AS phones

ON customers.id = phones.customer_id

答案 1 :(得分:1)

尝试这个

SELECT a.id,a.name , COUNT(b.id) AS no_of_contracts
FROM 
customers a JOIN contracts b ON a.id = b.customer_id 
GROUP BY a.id HAVING no_of_contracts > 1