提前道歉,我是(我的)SQL的新手 - 这应该是专家级DBA的一个简单问题 - 但我甚至不知道从哪里开始寻找解决方案。我甚至不确定我是否以正确的方式应用LEFT JOIN。
我的(DB)结构非常简单:
我有testsuite
个,并且有几个testcase
链接到每个testsuite
(“逻辑实体”)
在测试用例启动期间,我正在为testsuite
表格中的每个testsuiteinstance
创建一个条目,并为每个testcaseinstance
创建一个testcase
条目。
我的目标是获取属于某个testcaseinstance
testcase
的最后10 testsuite
个
这是我用来获取所有 testcaseinstances
的查询:
SELECT * FROM testcaseinstance AS tcinst
LEFT JOIN testsuiteinstance tsinst ON tsinst.id=tcinst.testsuiteinstance_id
LEFT JOIN testsuite ts ON ts.id=tsinst.testsuite_id
WHERE ts.id = 349 ORDER BY tcinst.id DESC;
所以,假设我在testcase
中有两个testsuite
,而testcase
每个都执行了100次。这个查询给了我200行。如果我在最后添加“LIMIT 10”,我将只获得一个testcase
类型的最后10行,但我想要20行(最后10-10属于两个testcase
s)
我很欣赏解决方案查询旁边的一些描述或指向“教程”的指针我可以开始查看与主题相关的内容(无论是什么:D)
提前致谢!
答案 0 :(得分:0)
这是一种方法;考虑这个(略设的)例子......
SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+
假设我们想要从此列表中返回前3个偶数和前3个奇数。暂时忽略这个特定例子的另一个更简单的解决方案,我们可以做这样的事情......
SELECT x.*
, COUNT(*) rank
FROM ints x
JOIN ints y
ON MOD(y.i,2) = MOD(x.i,2)
AND y.i >= x.i
GROUP
BY i
ORDER
BY MOD(x.i,2) DESC
, x.i DESC;
+---+------+
| i | rank |
+---+------+
| 9 | 1 |
| 7 | 2 |
| 5 | 3 |
| 3 | 4 |
| 1 | 5 |
| 8 | 1 |
| 6 | 2 |
| 4 | 3 |
| 2 | 4 |
| 0 | 5 |
+---+------+
从这里开始,抓住每组中前三名的过程变得微不足道......
SELECT x.*
, COUNT(*) rank
FROM ints x
JOIN ints y
ON MOD(y.i,2) = MOD(x.i,2)
AND y.i >= x.i
GROUP
BY i
HAVING rank <=3
ORDER
BY MOD(x.i,2),x.i DESC;
+---+------+
| i | rank |
+---+------+
| 8 | 1 |
| 6 | 2 |
| 4 | 3 |
| 9 | 1 |
| 7 | 2 |
| 5 | 3 |
+---+------+
......这可以简化为......
SELECT x.*
FROM ints x
JOIN ints y
ON MOD(y.i,2) = MOD(x.i,2)
AND y.i >= x.i
GROUP
BY i
HAVING COUNT(*) <=3;
+---+
| i |
+---+
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+