我有两个表:factors
和factor_items
。 FID
是factors
的主键和factor_items的外键。
有时我需要在factor
表上查看最新的factor_items
行及其对应的行。我怎样才能做到这一点?我知道我应该对这些表格进行JOIN
查询,但我对latest row(max FID)
没有任何想法:
SELECT * FROM factors INNER JOIN factor_items ON factors.FID = factor_items.FID;
答案 0 :(得分:3)
如果您包含WHERE
条件以检查最大ID,例如
SELECT * FROM factors
INNER JOIN factor_items
ON factors.FID = factor_items.FID
WHERE factors.FID IN ( select max(FID) from factors );
(OR)使用order by
和limit
子句
SELECT * FROM factors
INNER JOIN factor_items
ON factors.FID = factor_items.FID
order by factors.FID desc
limit 100;
答案 1 :(得分:1)
希望这会帮助你,尝试一下
SELECT * FROM factors
INNER JOIN factor_items ON factors.FID = factor_items.FID
WHERE factors.FID IN (select FID from factors ORDER BY FID desc limit 1);