怎样在SQL语句中使用EXISTS, UNIQUE, DISTINCT, 和OVERLAPS

本文介绍了如何使用EXISTS、UNIQUE、DISTINCT和OVERLAPS等谓词来修改SQL语句,以实现更复杂的查询需求,包括如何处理NULL值及不同数据库管理系统间的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



Within the WHERE clause lies many possibilities for modifying your SQL statement. Among these possibilities are the EXISTS, UNIQUE, DISTINCT, and OVERLAPS predicates. Here are some examples of how to use these in your SQL statements.

EXISTS

You can use the EXISTS predicate in conjunction with a subquery to determine whether the subquery returns any rows. If the subquery returns at least one row, that result satisfies the EXISTS condition, and the outer query executes. Consider the following example:

SELECT FirstName, LastName
 FROM CUSTOMER
 WHERE EXISTS
  (SELECT DISTINCT CustomerID
  FROM SALES
  WHERE SALES.CustomerID = CUSTOMER.CustomerID);

Here the SALES table contains all of your company’s sales transactions. The table includes theCustomerID of the customer who makes each purchase, as well as other pertinent information. The CUSTOMER table contains each customer’s first and last names, but no information about specific transactions.

The subquery in the preceding example returns a row for every customer who has made at least one purchase. The outer query returns the first and last names of the customers who made the purchases that the SALES table records.

EXISTS is equivalent to a comparison of COUNT with zero, as the following query shows:

SELECT FirstName, LastName
 FROM CUSTOMER
 WHERE 0 <>
  (SELECT COUNT(*)
  FROM SALES
  WHERE SALES.CustomerID = CUSTOMER.CustomerID);

For every row in the SALES table that contains a CustomerID that’s equal to a CustomerID in the CUSTOMER table, this statement displays the FirstName and LastName columns in the CUSTOMER table. For every sale in the SALES table, therefore, the statement displays the name of the customer who made the purchase.

UNIQUE

As you do with the EXISTS predicate, you use the UNIQUE predicate with a subquery. Although theEXISTS predicate evaluates to True only if the subquery returns at least one row, the UNIQUE predicate evaluates to True only if no two rows returned by the subquery are identical. In other words, theUNIQUE predicate evaluates to True only if all the rows that its subquery returns are unique.

Consider the following example:

SELECT FirstName, LastName
 FROM CUSTOMER
 WHERE UNIQUE
  (SELECT CustomerID FROM SALES
   WHERE SALES.CustomerID = CUSTOMER.CustomerID);

This statement retrieves the names of all new customers for whom the SALES table records only one sale. Because a null value is an unknown value, two null values aren’t considered equal to each other; when the UNIQUE keyword is applied to a result table that contains only two null rows, theUNIQUE predicate evaluates to True.

DISTINCT

The DISTINCT predicate is similar to the UNIQUE predicate, except in the way it treats nulls. If all the values in a result table are UNIQUE, then they’re also DISTINCT from each other.

However, unlike the result for the UNIQUE predicate, if the DISTINCT keyword is applied to a result table that contains only two null rows, the DISTINCT predicate evaluates to False. Two null values arenot considered distinct from each other, while at the same time they are considered to be unique.

This strange situation seems contradictory, but there’s a reason for it. In some situations, you may want to treat two null values as different from each other — in which case, use the UNIQUE predicate. When you want to treat the two nulls as if they’re the same, use the DISTINCT predicate.

OVERLAPS

You use the OVERLAPS predicate to determine whether two time intervals overlap each other. This predicate is useful for avoiding scheduling conflicts. If the two intervals overlap, the predicate returns a True value. If they don’t overlap, the predicate returns a False value.

You can specify an interval in two ways: either as a start time and an end time or as a start time and a duration. Here are some examples:

(TIME '2:55:00', INTERVAL '1' HOUR)
OVERLAPS
(TIME '3:30:00', INTERVAL '2' HOUR)

This first example returns a True because 3:30 is less than one hour after 2:55.

(TIME '9:00:00', TIME '9:30:00')
OVERLAPS
(TIME '9:29:00', TIME '9:31:00')

This example returns a True because you have a one-minute overlap between the two intervals.

(TIME '9:00:00', TIME '10:00:00')
OVERLAPS
(TIME '10:15:00', INTERVAL '3' HOUR)

This example returns a False because the two intervals don’t overlap.

(TIME '9:00:00', TIME '9:30:00')
OVERLAPS
(TIME '9:30:00', TIME '9:35:00')

This example returns a False because even though the two intervals are contiguous, they don’t overlap.



关于null和nique的关系可以参考:http://ocelot.ca/blog/blog/2013/09/11/null-and-unique/

DBMSMaximum number of NULLs when there is a UNIQUE constraint
IBM (DB2)One
InformixOne
IngresZero
InterBaseZero
Microsoft (SQL Server)One
MySQLMany [although the BDB storage engine was an exception]
OracleMany
SybaseOne

### 回答1: SQL Server PostgreSQL 的保留关键字有一些差异。其中,SQL Server 的保留关键字包括:ADD, ALTER, AS, ASC, AUTHORIZATION, BACKUP, BEGIN, BREAK, BROWSE, BULK, BY, CASCADE, CASE, CHECK, CHECKPOINT, CLOSE, CLUSTERED, COALESCE, COLLATE, COLUMN, COMMIT, COMPUTE, CONSTRAINT, CONTAINS, CONTAINSTABLE, CONTINUE, CONVERT, CREATE, CROSS, CURRENT, CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, CURRENT_USER, CURSOR, DATABASE, DBCC, DEALLOCATE, DECLARE, DEFAULT, DELETE, DENY, DESC, DISK, DISTINCT, DISTRIBUTED, DOUBLE, DROP, DUMP, ELSE, END, ERRLVL, ESCAPE, EXCEPT, EXEC, EXECUTE, EXISTS, EXIT, EXTERNAL, FETCH, FILE, FILLFACTOR, FOR, FOREIGN, FREETEXT, FREETEXTTABLE, FROM, FULL, FUNCTION, GOTO, GRANT, GROUP, HAVING, HOLDLOCK, IDENTITY, IDENTITY_INSERT, IDENTITYCOL, IF, IN, INDEX, INNER, INSERT, INTERSECT, INTO, IS, JOIN, KEY, KILL, LEFT, LIKE, LINENO, LOAD, MERGE, NATIONAL, NATURAL, NCHAR, NEXT, NOCHECK, NONCLUSTERED, NOT, NULL, NULLIF, OF, OFF, OFFSETS, ON, OPEN, OPENDATASOURCE, OPENQUERY, OPENROWSET, OPENXML, OPTION, OR, ORDER, OUTER, OVER, PERCENT, PLAN, PRECISION, PRIMARY, PRINT, PROC, PROCEDURE, PUBLIC, RAISERROR, READ, READTEXT, RECONFIGURE, REFERENCES, REPLICATION, RESTORE, RESTRICT, RETURN, REVERT, REVOKE, RIGHT, ROLE,ROLLBACK, ROWCOUNT, ROWGUIDCOL, RULE, SAVE, SCHEMA, SECURITYAUDIT, SELECT, SEMANTICKEYPHRASETABLE, SEMANTICSIMILARITYDETAILSTABLE, SEMANTICSIMILARITYTABLE, SESSION_USER, SET, SETUSER, SHUTDOWN, SOME, STATISTICS, SYSTEM_USER, TABLE, TABLESAMPLE, TEXTSIZE, THEN, TO, TOP, TRAN, TRANSACTION, TRIGGER, TRUNCATE, TRY_CONVERT, TSEQUAL, UNION, UNIQUE, UNPIVOT, UPDATE, UPDATETEXT, USE, USER, VALUES, VARYING, VIEW, WAITFOR, WHEN, WHERE, WHILE, WITH, WITHIN GROUP, WRITETEXT。 而 PostgreSQL 的保留关键字包括:ALL, ANALYSE, ANALYZE, AND, ANY, ARRAY, AS, ASC, ASYMMETRIC, AUTHORIZATION, BINARY, BOTH, CASE, CAST, CHECK, COLLATE, COLUMN, CONSTRAINT, CREATE, CROSS, CURRENT_CATALOG, CURRENT_DATE, CURRENT_ROLE, CURRENT_SCHEMA, CURRENT_TIME, CURRENT_TIMESTAMP, CURRENT_USER, DEFAULT, DEFERRABLE, DESC, DISTINCT, DO, ELSE, END, EXCEPT, FALSE, FETCH, FOR, FOREIGN, FREEZE, FROM, FULL, GRANT, GROUP, HAVING, ILIKE, IN, INITIALLY, INNER, INTERSECT, INTO, IS, ISNULL, JOIN, LATERAL, LEADING, LEFT, LIKE, LIMIT, LOCALTIME, LOCALTIMESTAMP, NATURAL, NOT, NOTNULL, NULL, OFFSET, ON, ONLY, OR, ORDER, OUTER, OVERLAPS, PLACING, PRIMARY, REFERENCES, RETURNING, RIGHT, SELECT, SESSION_USER, SIMILAR, SOME, SYMMETRIC, TABLE, TABLESAMPLE, THEN, TO, TRAILING, TRUE, UNION, UNIQUE, USER, USING, VARIADIC, VERBOSE, WHEN, WHERE, WINDOW, WITH。 以上是两种数据库的保留关键字的差异。 ### 回答2: SQL ServerPostgreSQL是两种常见的关系型数据库管理系统(RDBMS)。它们的保留关键字在某些情况下是有所不同的,下面是它们的差异: 1.关键字的数量:SQL ServerPostgreSQL之间的保留关键字数量是不同的。SQL Server拥有更多的保留关键字,这意味着在SQL Server中,您需要更小心地选择列名表名,以避免使用到这些保留关键字,否则可能会导致语法错误。 2.关键字的用途:两者之间还有一些保留关键字在用法上略有不同。例如,在SQL Server中,使用TOP来获取前几条记录,而在PostgreSQL中,使用LIMIT来实现相同的功能。这意味着,在从一个数据库系统迁移到另一个数据库系统时,您可能需要更改您的查询以适应不同的保留关键字。 3.大小写敏感性:在SQL Server中,保留关键字是不区分大小写的,而在PostgreSQL中,保留关键字是区分大小写的。这意味着在使用PostgreSQL时,必须严格按照保留关键字的大小写编写查询,否则可能会导致语法错误。 总体而言,SQL ServerPostgreSQL在保留关键字方面存在一些差异,包括关键字的数量、用途大小写敏感性。在编写查询时,要特别注意这些差异,以避免语法错误查询失败。 ### 回答3: SQL ServerPostgreSQL是两种不同的关系型数据库管理系统,它们在保留关键字方面存在一些差异。 首先,在SQL Server中,一些常用的保留关键字包括:SELECT、INSERT、UPDATE、DELETE、WHERE、FROM、JOIN、GROUP BY、HAVING、ORDER BY等。这些关键字用于执行查询、插入、更新删除操作,以及过滤、排序分组数据。此外,SQL Server还有一些特定的保留关键字,例如TOP、AS、INNER JOIN、OUTER JOIN、UNION等。 而在PostgreSQL中,保留关键字的列表与SQL Server有些不同。PostgreSQL的保留关键字包括:SELECT、INSERT、UPDATE、DELETE、WHERE、FROM、JOIN、GROUP BY、HAVING、ORDER BY等,这些与SQL Server相同。但是,PostgreSQL还有一些额外的保留关键字,如VALUES、RETURNING、GRANT、CASE、CAST等。 此外,两者在保留关键字的使用语法上也存在一些差异。在SQL Server中,保留关键字通常不区分大小写,因此可以使用大写或小写或其组合来表示关键字。而在PostgreSQL中,保留关键字是不区分大小写的,但建议使用小写来表示。此外,在PostgreSQL中,如果需要使用与保留关键字相同的名称作为表名或列名,可以使用双引号将其括起来,以区分为标识符而不是关键字。 总结而言,SQL ServerPostgreSQL在保留关键字方面存在一些差异。尽管它们有许多相同的关键字,但两者都有一些特定的关键字语法上的差异。在编写SQL查询语句时,要注意了解遵守所使用的数据库管理系统的保留关键字的规则约束。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值