从具有clouse计数的两个表中选择

时间:2015-03-24 01:57:37

标签: sql select

table1:

+-------------+-----------+--------+
| Cust_id     | cust_name | car_id |
+-------------+-----------+--------+
|           1 | A         |      1 |
|           2 |   B       |      1 |
|           2 |     C     |      3 | 
+-------------+-----------+--------+

表2:

+-------------+---------+
| car_id      | name_car|
+-------------+---------+
|           1 | TOYOTA  |
|           2 | HONDA   |
+-------------+---------+

如何选择在table1中有两次使用的name_car,如

+-------------+
| name_car    |
+-------------+
|  TOYOTA     |
+-------------+

以及如何查看:

+-------------+---------+
| name_car    | COUNT   |
+-------------+---------+
|  TOYOTA     | 2       |
|  HONDA      | 1       |
+-------------+---------+

2 个答案:

答案 0 :(得分:1)

select t2.name_car, count(name_car)
from table1 t1
inner join table2 t2 on t2.car_id = t1.car_id
group by t2.name_car

答案 1 :(得分:0)

  

如何选择table1中有两次使用的name_car

select q.name_car
from (
     select t2.name_car,count(t1.car_id) cnt
     from table1 t1
     join table2 t2 on t1.car_id=t2.car_id
     group by t1.name_car
 ) q
where q.cnt=2
  

以及如何查看:

select t2.name_car,count(t1.car_id)
from table1 t1
join table2 t2 on t1.car_id=t2.car_id
group by t1.name_car