Oracle如何检查某个特定的id是否存在于多个表中以及哪些表中存在?
我有一个名为 persons
的表,其主键是 pid
,我有 3 个不同的表(我们称它们为 A
、B< /code> 和
C
),其中 pid
是外键。
我需要知道这些表中是否存在特定的 pid
以及具体是哪些表。
我不知道这是否可以通过单个查询来实现,但我认为在我的特定情况下,一个函数会更好地工作,这样我就可以这样做:
SELECT pid, name, sex, func_name(pid) my_str
FORM persons
WHERE pid = 5
然后,根据找到 pid 的表,my_str
类似于:
B | C
意思是在表 B
和 C
上找到了 pid = 5
。
我可以使用 COUNT(*) 在函数中执行 3 个 SELECT 来完成此操作。如果结果是> 0,然后从相应的 SELECT 中在表中找到 pid = 5
。但这似乎是一种愚蠢的方法,有建议吗?
I have a table named persons
which the primary key is pid
than I have 3 different tables (let's call them A
, B
and C
) where pid
is a foreign key.
I need to know if a specific pid
exists in any of those tables and exactly which of them.
I don't know if this is achievable with a single query but I'm thinking that a function would work better in my specific case so that I could do this:
SELECT pid, name, sex, func_name(pid) my_str
FORM persons
WHERE pid = 5
And then, depending on the tables that pid is found, my_str
would be something like:
B | C
Meaning pid = 5
was found on tables B
and C
.
I could do this with 3 SELECTs in the function, using COUNT(*). If the result is > 0, then pid = 5
was found on the table from the respective SELECT. But this seems a stupid way to do it, suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像下面这样的东西对你有用吗?我刚刚添加了 case/whens 来向您展示如何测试其他表中是否存在。
Would something like the following do the trick for you? I just added case/whens to show you how you could test for existance in the other tables.
对 @Ronnis 答案的增强(我没有测试它,但我希望这样的东西会起作用。如果没有,请原谅我迟到了:))
An enhancement to @Ronnis 's answer (I didn't test it, but I hope something like this will work. If not, forgive me for the late hour :) )