Reputation: 25
I have these tables in my MySQL database:
Cars table:
+----Cars Table-----+
+---------------------+
| id | BMW | KIA |-and another cars
+----+----------+-----+
| 1 | M5 | Rio |
| 2 | Z1 | Serato |
| 3 | X5 | Sorento|
Like table:
+----------------------+-----+
| id | Cars_id| Cars |ip |
+----+----------+------+-----+
| 1 | 1 | KIA |1.0.1|
| 2 | 1 | BMW |1.0.1|
Basically, the Cars table have more cars Mark and their models.
My question is, how Join this tables - Like.Cars_id=Cars.id and Like.Cars=Cars.Column names?.
So, I would like a query like this:
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?
Upvotes: 1
Views: 54
Reputation: 133370
you should normalize the table this way
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
in this way is easy get the like for car but also like for brand and others
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
Upvotes: 1
Reputation: 31993
if you just want to count cars model ip
then no need join between two tables,below query will count model ip
select Cars, count(ip) from Like_table
group by Cars
Upvotes: 0