从sql查询中获取第一个/第二个/第三个元素

时间:2016-06-05 11:13:58

标签: mysql sql

我有像

这样的SQL查询
SELECT id FROM chart WHERE name='qwertz' AND run_id=3

我知道此查询将返回3个数据集。对于另一个复杂的查询,我需要返回上面的查询的第一个/第二个/第三个id,如

SELECT value FROM data WHERE id=(SELECT id FROM chart WHERE name='qwertz' AND run_id=3).getFirst

 SELECT value FROM data WHERE id=(SELECT id FROM chart WHERE name='qwertz' AND run_id=3).getSecond

 SELECT value FROM data WHERE id=(SELECT id FROM chart WHERE name='qwertz' AND run_id=3).getThird

我该怎么做?

1 个答案:

答案 0 :(得分:3)

您可以将OFFSETLIMIT

一起使用
SELECT * FROM chart
WHERE name = 'qwertz' and run_id = 3
LIMIT 1,0 -- First record

SELECT * FROM chart
WHERE name = 'qwertz' and run_id = 3
LIMIT 1,1 -- Second record

SELECT * FROM chart
WHERE name = 'qwertz' and run_id = 3
LIMIT 1,2 -- Third record

虽然没有特定的ORDER BY子句,但这将是随机记录!

也可以写成一个查询来将所有这些组合在一起:

SELECT * FROM chart
WHERE name = 'qwertz' and run_id = 3
LIMIT 3 -- First 3