我有两个表:tableA (idA, titleA),tableB (idB, idA, textB)它们之间是一对多的关系。对于tableA中的每一行,我想检索tableB中对应的最后5行(按idB排序)。
tableA (idA, titleA)
tableB (idB, idA, textB)
我试过了
SELECT * FROM tableA INNER JOIN tableB ON tableA.idA = tableB.idA LIMIT 5
但这只是限制了INNER JOIN的全局结果,而我想限制每个不同tableA.id的结果
我怎样才能做到这一点 ?
谢谢
我认为这是您需要的:
SELECT tableA.idA, tableA.titleA, temp.idB, temp.textB FROM tableA INNER JOIN ( SELECT tB1.idB, tB2.idA, ( SELECT textB FROM tableB WHERE tableB.idB = tB1.idB ) as textB FROM tableB as tB1 JOIN tableB as tB2 ON tB1.idA = tB2.idA AND tB1.idB >= tB2.idB GROUP BY tB1.idA, tB1.idB HAVING COUNT(*) <= 5 ORDER BY idA, idB ) as temp ON tableA.idA = temp.idA
有关此方法的更多信息,请参见:
http://www.sql-ex.ru/help/select16.php