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

时间:2018-01-10 14:41:46

标签: mysql sql

我有两张表:CarRent

+----------+-----------+---------+--------+
| 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

1 个答案:

答案 0 :(得分:1)

这应该有效:

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
)