如何解决此查询?

时间:2013-03-29 21:50:57

标签: mysql sql database

有人可以帮助解决这个问题:

列出所有具有多个米的客户。

我是一个完整的新手,请原谅我,如果这是一个容易解决的问题..

Customers – minimum 20 records
Meters – min. 30 records
Meter Readings – min. 100 readings
Invoices – 1 per Meter Reading

我尝试了以下查询但没有成功......

select *
from Customers
LEFT OUTER JOIN Meters ON Customers.idCustomers = Meters.Customers_idCustomers
where Customers.idCustomers = Customers.idCustomers;

我还尝试过SELECT CASE查询

谢谢!

2 个答案:

答案 0 :(得分:1)

这是一种方式:

select c.*
from customers c
where c.idCustomer in (select idCustomer
                       from Meters
                       group by Customers_idCustomers
                       having count(*) > 1
                      )

在MySQL中,您还可以通过以下方式将其表达为与群组的联接:

select c.*
from customers c join
     meters m
     on c.idCustomer = m.Customers_idCustomer
group by c.idCustomer
having count(*) > 1

答案 1 :(得分:0)

这是GROUP BY子句的用武之地!

select customers.*, count(*) meter_count
from customers
inner join meters on customers.idCustomer = meters.idCustomer
group by customers.idCustomer
having meter_count > 1