获取id相对于其他外键最大的行

a9wyjsp7  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(190)

我有两张table: Car 以及 Rent ```
+----------+-----------+---------+--------+
| pk_carid | fk_rentid | name | status |
+----------+-----------+---------+--------+
| 1 | 1 | toyota | gone |
+----------+-----------+---------+--------+
| 2 | 2 | tata | here |
+----------+-----------+---------+--------+
| 3 | 3 | ferrri | here |
+----------+-----------+---------+--------+
| 4 | 1 | toyota | here |
+----------+-----------+---------+--------+
| 5 | 2 | tata | gone |
+----------+-----------+---------+--------+
| 6 | 3 | ferrrii | gone |
+----------+-----------+---------+--------+

我想把唱片拿到哪儿去 `pk_cardid` 是4、5或6,但不是1、2或3。
我尝试了以下查询,但它只是给我一个记录的最后一行,其中 `pk_carid = 6` .

SELECT c.cardid
,r.rentid
,c.name,
FROM cars AS c
INNER JOIN rent AS r
ON r.rentid = c.carid
WHERE (c.carid =(SELECT MAX(c2.carid) Expr1 FROM cars c2 )) group by r.rentid

q3qa4bjr

q3qa4bjr1#

这应该起作用:

select cars.* from cars
join
(
   select max(carid) as id  
   from cars 
   group by rentid
)as maxCar on maxCar.id = cars.carid

或者你可以试试

select * from cars
where carid in
(
   select max(carid) as id  
   from cars 
   group by rentid
)

相关问题