MySql用列名联接两个表

时间:2018-08-26 08:20:28

标签: mysql sql

我的MySQL数据库中有这些表:

汽车表:

+----Cars   Table-----+
+---------------------+
| id | BMW   | KIA    |-and another cars
+----+----------+-----+
| 1  | M5    | Rio    |
| 2  | Z1    | Serato |
| 3  | X5    | Sorento|

喜欢桌子:

+----------------------+-----+
| id | Cars_id| Cars   |ip   |
+----+----------+------+-----+
| 1  |   1    | KIA    |1.0.1|
| 2  |   1    | BMW    |1.0.1|

基本上,“汽车”表中有更多的汽车Mark及其模型。

我的问题是,如何联接此表-Like.Cars_id = Cars.id和Like.Cars = Cars.Column名称?。

所以,我想要这样的查询:

SELECT Cars.BMW, Cars.KIA,  COUNT(Like.ip) AS likes
FROM CARS_Table
    LEFT JOIN Like_table
        ON Cars.id = Like.Cars_id AND what?

2 个答案:

答案 0 :(得分:1)

您应该以这种方式标准化表格

Brand 
id, name  
1, BMW 
2, KIA 
3, ...

cars 
id, id_brand, car_name 
1, 1, M5 
2, 1, Z1 
3, 1, X5 
4, 2, Rio 
5, 2, Serato 
6, 2, Sorento 

like_table  

id, cars_id, ip 
1, 1, 1.0.1 
2, 1, 1.0.1 


select b.name, c.name, count(ip)
from  like_table l 
inner join  cars c on l.cars_id = c.id 
inner join  Brand b on b.id = c.id_brand
group by b.name, c.name 

通过这种方式很容易获得汽车喜欢的东西,但也获得品牌和其他人的喜欢

select b.name count(ip)
from  like_table l 
inner join  cars c on l.cars_id = c.id 
inner join  Brand b on b.id = c.id_brand
group by b.name

答案 1 :(得分:0)

如果您只想计算ip型汽车

然后不需要在两个表之间进行联接,下面的查询将计算模型ip

select Cars,  count(ip) from Like_table    
group by Cars