在select中使用select创建mysql例程游标
我有一张如下表:在select中使用select创建mysql例程游标,mysql,select,if-statement,Mysql,Select,If Statement,我有一张如下表: id gnome dead ----------------- 1 pet yes 2 pet no 3 pet no 4 kin no 5 kin yes 6 kin no SELECT * FROM my_table; +----+-------+------+ | id | gnome | dead | +----+-------+------+ | 1 | pet | yes |
id gnome dead
-----------------
1 pet yes
2 pet no
3 pet no
4 kin no
5 kin yes
6 kin no
SELECT * FROM my_table;
+----+-------+------+
| id | gnome | dead |
+----+-------+------+
| 1 | pet | yes |
| 2 | pet | no |
| 3 | pet | no |
| 4 | kin | no |
| 5 | kin | yes |
| 6 | kin | no |
| 7 | cat | no |
| 8 | cat | yes |
| 9 | uno | no |
| 10 | uyes | yes |
+----+-------+------+
现在,我想在例程中创建一个光标:
1死亡的所有行是
2行,其中dead为no,前提是之前同一个侏儒没有dead=yes
结果应该是:
id gnome dead
-----------------
1 pet yes
4 kin no
5 kin yes
好的,我想我找到了解决办法
SELECT * FROM asd AS t WHERE dead = 'yes' OR NOT EXISTS(SELECT k.dead FROM asd as k WHERE k.id < t.id AND t.gnome = k.gnome and k.dead = 'yes')
我在这里创作了一把小提琴:
你觉得怎么样?在常规游标中是否正常?您的解决方案似乎不符合您的要求。以下是一个解决方案:
SELECT *
FROM my_table
WHERE dead = 'yes'
UNION
SELECT x.*
FROM my_table x
LEFT
JOIN my_table y
ON y.gnome = x.gnome
AND y.dead = 'yes'
AND y.id < x.id
WHERE x.dead = 'no'
AND y.id IS NULL;
您是否希望返回第9行?并且您特别希望为此使用游标?到目前为止您所执行的代码在哪里?@WorkSmarter刚刚粘贴了我正在处理的小提琴。我想如果这在选择中起作用,那么光标也应该起作用。很酷,谢谢。。。我想我只需要凭身份证订购,它应该是完美的。你能解释一下我的解决方案哪里会失败吗?只是为了更好地理解你想要的东西。您的查询似乎同时返回这两个值。一个更具代表性的数据集可能会更好地说明这个问题。mmm仍然没有得到它,您能说明在哪种情况下它会失败吗?无论如何,我会用你的解决方案!感谢您的编辑,我需要第1、4、5、7、8、9、10行,两个解决方案看起来都返回sameWell,也许我搞错了。