[英]MySQL relation between tables
Hey so I have a question. 嘿所以我有一个问题。 I have two tables.
我有两张桌子。 table1 and table2.
table1和table2。 table1:
表格1:
id | car_numbers | type | model | type_id
1 3 bmw <model1> 1
2 5 bmw <model2> 1
3 2 mercedes <model1> 2
4 4 mercedes <model2> 2
5 1 chevrolet <model1> 3
table2: 表2:
id | price | type_id
1 100 1
2 200 1
3 300 2
4 400 2
5 500 3
What I want, is to display the 'type', the 'car_numbers' and the average price of each car type. 我想要的是显示'类型','car_numbers'和每种车型的平均价格。 Basically the result of what I want between those two tables is:
基本上我想要在这两个表之间的结果是:
type | car_numbers | average_price
bmw 8 150
mercedes 6 350
chevrolet 1 500
How can I do that? 我怎样才能做到这一点? I know I have to relate to the type_id that's common in both tables but how can I do that?
我知道我必须与两个表中常见的type_id相关但我该怎么做呢?
I think it might be this you are looking for 我想你可能正在寻找这个
SELECT t.name, sum(Distinct o.car_number) car , avg(w.price) price FROM
TYPE t
INNER JOIN tone AS o ON o.type_id = t.id
INNER JOIN ttwo AS w ON w.type_id = t.id
GROUP BY t.name
http://sqlfiddle.com/#!2/1937a/51 http://sqlfiddle.com/#!2/1937a/51
Is this what you are looking for, usage of Group By and Avg: 这是你在寻找,使用Group By和Avg:
SELECT type, car_numbers, avg(price) AS average_price
FROM table1 T1
INNER JOIN table2 T2
ON T1.type_id = T2.type_id
GROUP BY type, car_numbers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.