我有两张表: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
答案 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
)