HAVING 子句
语法:
SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s) HAVING condition ORDER BY column_name(s);
假设还是有custorm表如下
列出了每个国家/地区的客户数量。仅包括拥有超过 5 个客户的国家/地区:
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5;
列出了每个国家的客户数量,从高到低排序(仅包括客户超过 5 个的国家):
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5 ORDER BY COUNT(CustomerID) DESC;
EXISTS 运算符
EXISTS运算符用于测试子查询中是否存在任何记录。
EXISTS运算符返回true,如果子查询返回一个或多个记录。
语法
SELECT column_name(s) FROM table_name WHERE EXISTS (SELECT column_name FROM table_name WHERE condition);
假设我们还是用到product表
suppiler表
例如:
返回 TRUE 并列出产品价格小于 20 的供应商:返回如下
SELECT SupplierName FROM Suppliers WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);
返回如下
返回 TRUE 并列出产品价格等于 22 的供应商:
SELECT SupplierName FROM Suppliers WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price = 22);
返回为:
注释
单行注释以–.
– 和行尾之间的任何文本都将被忽略(不会被执行)
例如:
--Select all: SELECT * FROM Customers;
又例如
SELECT * FROM Customers -- WHERE City='Berlin';
多行注释/*以 /.
/ 和 */ 之间的任何文本都将被忽略。
例如:
/*Select all the columns of all the records in the Customers table:*/ SELECT * FROM Customers;
又例如
/*SELECT * FROM Customers; SELECT * FROM Products; SELECT * FROM Orders; SELECT * FROM Categories;*/ SELECT * FROM Suppliers;
忽略语句的一部分:
例如
SELECT CustomerName, /*City,*/ Country FROM Customers;
又例如
SELECT * FROM Customers WHERE (CustomerName LIKE 'L%' OR CustomerName LIKE 'R%' /*OR CustomerName LIKE 'S%' OR CustomerName LIKE 'T%'*/ OR CustomerName LIKE 'W%') AND Country='USA' ORDER BY CustomerName;
运算符
其实这一节内容,我已经在前面的运算符都演示过了。再说一下呗。
算术运算符有
演示一部分
比如求20+30:
SELECT 30 + 20;
除法(返回3)
SELECT 30 / 10;
取余数(返回2)
SELECT 17 % 5;
比较运算符
演示一部分
大于
SELECT * FROM Products WHERE Price = 18;
不等于
SELECT * FROM Products WHERE Price <> 18;
大于等于
SELECT * FROM Products WHERE Price >= 30;