Mysql - 如何改进此查询?

时间:2014-11-13 07:16:12

标签: mysql database

我有两个表:factorsfactor_itemsFIDfactors主键和factor_items的外键

有时我需要在factor表上查看最新的factor_items行及其对应的行。我怎样才能做到这一点?我知道我应该对这些表格进行JOIN查询,但我对latest row(max FID)没有任何想法:

SELECT * FROM factors INNER JOIN factor_items ON factors.FID = factor_items.FID;

2 个答案:

答案 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 bylimit子句

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);