select * from table where vendor_id in (1, 2); select * from table where vendor_id not in (1, 2);
in 表示在范围内的数据,not in 表示不在范围内的数据
3. 通配符
like 操作符指示 MySQL 后跟的搜索模式利用通配符匹配。根据 MySQL 配置,搜索可以是区分大小写的
% 表示任何字符出现任意次数(包括 0 个字符)。注意 % 不能匹配 NULL
_(下划线)只能匹配一个字符
4. 正则表达式
regexp 后面可以作为正则表达式。正则表达式匹配不区分大小写。
1 2 3 4 5
select * from table where prod_name regexp '.000'; // . 表示匹配任意一个字符
// like 和 regexp。如果匹配的文本在列值中出现,like 将不会找到他(除非使用通配符);但 regexp 会找到他 select * from table where prod_name like '1000'; select * from table where prod_name regexp '1000';
select vend_name, prod_name, prod_price from vendors inner join products on vendors.vend_id = products.vend_id;
2. 自联结
1 2 3
select p1.prod_id, p1.prod_name from products as p1, products as p2 where p1.vend_id = p2.vend_id and p2.prod_id = 'DTINTR';
如上,词查询要求首先找到生产 ID 为 DINTR 的物品的供应商,然后找到这个供应商生产的其他物品。
1 2
select prod_id, prod_name from products where vend_id = (select vend_id from products where prod_id = 'DTNTR');
如上使用子查询也可以达到目的,有时候处理联结远比处理子查询快得多
3. 外部联结
1 2 3
select customers.cust_id, orders.order_num from customers left outer join orders on customers.cust_id = orders.cust_id;
与内部联结不同的是,外部联结包括没有关联行的行。
在使用 outer join 语法时,必须使用 right 或 left 关键字指定包含其所有行的表(right 指出的是 outer join 右边的表,而 left 指出的是 outer join 左边的表)
七、组合查询
union:指示 MySQL 执行两条 select 语句,并把输出组合成单个查询结果集
1 2 3
select vend_id, prod_id, prod_price from products where prod_price <= 5 union select vend_id, prod_id, prod_price from products where vend_id in (1001, 1002);
在使用 union 时,重复的行被自动取消。如果想要返回所有匹配的行,可使用 union all
1 2 3 4
select vend_id, prod_id, prod_price from products where prod_price <= 5 union select vend_id, prod_id, prod_price from products where vend_id in (1001, 1002) order by vend_id, prod_price;
如上,如果要对输出用 order by 子句排序。在用 union 组合查询时,只能使用一条 order by 子句,它必须出现在最后一条 select 语句之后。因为对于结果集,不存在用一种方式排序一部分,而又用另一种方式排序另一部分的情况,因此不允许使用多条 order by 子句。