带有虚拟行的 SQL in 子句
我真的很想知道是否可以执行一个 select 语句,该语句返回与我们放入 in 子句中完全相同的记录?
示例:
select * from table
where table_id in (1, 2, 3, 666);
此表的示例只有 id-s 从 1 到 100,因此此选择将仅返回三行。我需要做什么才能获得 666 的一行(可能为空或虚拟)?
谢谢!
I'd really like know if it's possible to do a select statement, which returns exactly same records, that we put into in clause?
Sample:
select * from table
where table_id in (1, 2, 3, 666);
This table for an example has only id-s from 1 to 100, so this select will return only three rows. What I need to do, to get also one (probably null or dummy) row for 666?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 union:
在 Oracle 中可以这样做。
from Dual
可能会有所不同,具体取决于您使用的数据库系统。请注意,如果您使用联合,您的虚拟查询必须选择与真实查询相同的记录。
You could use union:
is how you could do it in Oracle. The
from dual
might vary depending on what database system you're using.Just be aware that if you use union, your dummy query MUST select the same records as the real query.
您可以在没有表的情况下进行选择
只需对查询进行 UNION
You can select without a table
Just do a UNION with your query
假设一个表
numbers
包含从 1 到 1000000 的所有数字(实际上足以覆盖您的输入值范围),您可以运行以下 SQL:如果您使用的 DBMS 提供更好的解决方案,例如 SQL Anywhere 的 sa_rowgenerator 过程,可以用过程调用替换表
numbers
,并且没有最大数量的限制。Assuming a table
numbers
containing all numbers from, say, 1 to 1000000 (in fact enough that your range of input values is covered), you could run the following SQL:If you use a DBMS that offers a better solution, like e. g. SQL Anywhere with it's sa_rowgenerator procedure, you can replace the table
numbers
with a procedure call, and do not have a limit of a maximum number.IN
子句是一个布尔谓词,因此您需要将其替换为虚拟记录集:在
SQL Server 2008
中,您可以运行此查询:使用
@ mydate
是一个表变量,作为参数从客户端传递。在
PostgreSQL
中,您可以运行以下查询:其中
:arr
是一个数组[1, 2, 3, 666]
,也是从客户端作为参数。在
Oracle
中,您可以执行以下操作:,其中
:mycol
是从客户端传递的集合类型的变量。IN
clause is a boolean predicate, so you'll need to replace it with a dummy recordset:In
SQL Server 2008
, you can run this query:with
@mydate
is a table variable, passed as a parameter from the client.In
PostgreSQL
, you can run this query:where
:arr
is an array[1, 2, 3, 666]
, also passed from the client as the parameter.In
Oracle
, you can do:, where
:mycol
is a variable of collection type, passed from the client.一种思考方式是:您需要让该数据作为数据集“输入”查询。在 where 子句中找到的数据永远不会“添加”到查询中,它们仅用于过滤掉现有数据。
一个简单的例子:
One way to think of it is: you'd need to have that data "enter" the query as a data set. Data found in where clauses is never "added" to the query, they are only used to filter existing data out.
A quick example: