如何在 ANSI SQL 中进行 EXISTS 选择
是否有跨数据库(至少是 SQL Server、Oracle、Postgre、MySQL、SQLite)的方式来执行我在 T-SQL 中执行的操作,
SELECT 1 WHERE EXISTS (SELECT * FROM Foo WHERE Bar = 'Quux')
这似乎不是有效的 ANSI SQL 语法,因为没有 FROM 子句。目前我正在使用 COUNT(*) 来执行此操作,但我认为这不是最佳选择。
Is there a cross-database (at least SQL Server, Oracle, Postgre, MySQL, SQLite) way of doing what I would do in T-SQL using
SELECT 1 WHERE EXISTS (SELECT * FROM Foo WHERE Bar = 'Quux')
It seems that this is not valid ANSI SQL syntax because there is no FROM clause. At present I am using COUNT(*) to do this, but I don't think that's optimal.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
子查询是不必要的——使用:
更复杂的版本,使用aggregates &案例表达:
The subquery is unnecessary - use:
A more complicated version, using aggregates & CASE expression:
有点作弊,但这应该可以工作,并且除了最愚蠢的 DBMS 之外的所有 DBMS 都应该对
DISTINCT 1 FROM Foo
进行简单的优化!从 Foo WHERE EXISTS 中选择 DISTINCT 1(SELECT * FROM Foo WHERE Bar = 'Quux')
Cheating a little, but this ought to work and the
DISTINCT 1 FROM Foo
should be trivially optimized by all but the dumbest of DBMSs!SELECT DISTINCT 1 FROM Foo WHERE EXISTS (SELECT * FROM Foo WHERE Bar = 'Quux')
只需使用 COUNT 即可,除非您另有需要。假设对 Bar 和索引有良好的选择性,它不会太重要,但可读性会更高。
当然,您会为了可移植性而牺牲优化,因此在这种情况下使用 COUNT
Just use COUNT until you need otherwise. Assuming good selectivity on Bar and and index, it won't matter too much but will be far more readable
You will trade optimisation for portability of course, so in this case use COUNT