如何在两个 MySQL 表之间进行计数和连接?
How to count and join between two MySQL tables?
我想写出一辆车被租用的次数,但我无法让它工作,我有两个表。一个叫做 vehicle
,另一个叫做 rental
。
In rental 是您预订汽车时所有 "rentings" 去的地方,所有车辆都存储在 vehicle 中。这是我所做的几乎有效的查询。
SELECT vehicle.id,COUNT(rental.vid) as rented,IFNULL(rental.vid,0) as nothing, vehicle.make as make, vehicle.model as model, vehicle.regnr as regnr, vehicle.color as color, vehicle.state as state, vehicle.imgurl as img, vehicle.description as description, vehicle.id
FROM rental,vehicle
WHERE vid = vehicle.id GROUP BY vid
并将打印出:
其余没有价值的(从未出租过)不存在,我用 IFNULL
尝试了很多不同的方法,但没有任何进展。
Select
从 Vehicle
table 和 Left Join
到 Rental
table。这将包括从未租用过的车辆,它们的计数 (rental.vid) 将为 0:
SELECT vehicle.id
,COUNT(rental.vid) as rented
, vehicle.make as make
, vehicle.model as model
, vehicle.regnr as regnr
, vehicle.color as color
, vehicle.state as state
, vehicle.imgurl as img
, vehicle.description as description
FROM vehicle
left join rental on vid = vehicle.id
GROUP BY vehicle.id
示例中的隐式连接等同于 inner join
。向左加入 select 您想要从源 table 获得的所有行。如果您要加入的 table 有匹配项,它们也会出现。这是将数据附加到源 table.
的好方法
我想写出一辆车被租用的次数,但我无法让它工作,我有两个表。一个叫做 vehicle
,另一个叫做 rental
。
In rental 是您预订汽车时所有 "rentings" 去的地方,所有车辆都存储在 vehicle 中。这是我所做的几乎有效的查询。
SELECT vehicle.id,COUNT(rental.vid) as rented,IFNULL(rental.vid,0) as nothing, vehicle.make as make, vehicle.model as model, vehicle.regnr as regnr, vehicle.color as color, vehicle.state as state, vehicle.imgurl as img, vehicle.description as description, vehicle.id
FROM rental,vehicle
WHERE vid = vehicle.id GROUP BY vid
并将打印出:
其余没有价值的(从未出租过)不存在,我用 IFNULL
尝试了很多不同的方法,但没有任何进展。
Select
从 Vehicle
table 和 Left Join
到 Rental
table。这将包括从未租用过的车辆,它们的计数 (rental.vid) 将为 0:
SELECT vehicle.id
,COUNT(rental.vid) as rented
, vehicle.make as make
, vehicle.model as model
, vehicle.regnr as regnr
, vehicle.color as color
, vehicle.state as state
, vehicle.imgurl as img
, vehicle.description as description
FROM vehicle
left join rental on vid = vehicle.id
GROUP BY vehicle.id
示例中的隐式连接等同于 inner join
。向左加入 select 您想要从源 table 获得的所有行。如果您要加入的 table 有匹配项,它们也会出现。这是将数据附加到源 table.