SELECT prod_name FROM Products;
SELECT prod_name , prod_id , prod_price FROM Products;
SELECT * FROM Products;
检索一列,多列,所有列
SELECT DISTINCT vend_id FROM Products;
只返回不同的vend_id行
SELECT TOP 5 prod_name FROM Products; --SQL Server、Access
SELECT prod_name FROM Products FETCH FIRST 5 ROWS ONLY; --Oracle
SELECT prod_name FROM Products LIMIT 5; -- MySQL 、MariaDB、 PostgreSQL
SELECT prod_name FROM Products LIMIT 5 OFFSET 5; --返回从第5行开始的5行数据
ORDER BY 一定要写在不同组合的语句最后
SELECT prod_name FROM Products ORDER BY prod_name;
SELECT prod_name, prod_id , prod_price FROM Products
ORDER BY prod_price ,prod_name; --优先prod_price排序,其次prod_name
SELECT prod_name, prod_id , prod_price FROM Products
ORDER BY 2 ,3;
按列位置排序。 优点:方便写。 缺点:可读性不高。
SELECT prod_name, prod_id , prod_price FROM Products
ORDER BY prod_price ,prod_name DESC;
DESC(descending) 降序排序
SELECT prod_name, prod_id , prod_price FROM Products
ORDER BY prod_price DESC ,prod_name; --混合排序
SELECT prod_name , prod_price FROM Products
WHERE prod_price = 3.49;
操作符 | 说明 |
---|---|
= | 等于 |
<> 、!= | 不等于 |
< | 小于 |
<= | 小于等于 |
!< | 不小于 |
> | 大 |
= |
大于等于 |
!> | 不大于 |
BETWEEN | 在指定的两数之间 |
IS NULL | 为NULL值 |
SELECT prod_name , prod_price FROM Products
WHERE prod_price< 10;
SELECT prod_name , prod_price FROM Products
WHERE prod_price BETWEEN 5 AND 10;
SELECT vend_id , prod_name FROM Products
WHERE vend_id <> 'DLL01';
Access不支持!=
SELECT prod_name FROM Products
WHERE prod_price is NULL;
SELECT vend_id , prod_name FROM Products
WHERE vend_id <> 'DLL01' AND prod_price <=4;
SELECT vend_id , prod_name FROM Products
WHERE vend_id <> 'DLL01' OR prod_price <=4;
SELECT vend_id , prod_name FROM Products
WHERE (end_id <> 'DLL01' OR vend_id <> 'BRS01')
AND prod_price <=4 ;
SELECT prod_price , prod_name FROM Products
WHERE vend_id IN ('DLL01' 'BRS01')
ORDER BY prod_name; --IN 比 OR操作更快
SELECT prod_name FROM Products
WHERE NOT vend_id ='DLL01'
ORDER BY prod_name; --NOT等价于<>,但是在复杂语句更有用
谓词(oredicate) 操作符作为谓词时它不是操作符,从技术上来说LIKE是谓词
SELECT prod_id ,prod_name FROM Products
WHERE prod_name LIKE 'Fish%' --Access需使用*
SELECT prod_id ,prod_name FROM Products
WHERE prod_name LIKE '%bean bag%';
SELECT prod_id ,prod_name FROM Products
WHERE prod_name LIKE 'F%y';
注意许多DBMS会用空格填充字段内容,Fish bean bag toy其实是以空格结尾的,
可能会检查不出来,最好使用F%y%
只匹配单个字符
SELECT prod_id ,prod_name FROM Products
WHERE prod_name LIKE '_ish bean bag toy';
方括号通配符用来指定一个字符集
SELECT cust_contact FROM Customers
WHERE cust_contact LIKE '[JM]%'
ORDER BY cust_contact;
SELECT cust_contact FROM Customers
WHERE cust_contact LIKE '[^JM]%'
ORDER BY cust_contact;
[JM]匹配括号中的任意一个字符,只能匹配单个字符
通配符比前面搜索要耗费更长的处理时间