mysql [not] exists 子查询应用
阅读(354)
2018-02-15
在嵌套查询中,常会遇到exists或not exists 运算符,它表示一个子查询是否存在。如果子查询中能返回至少一行,则表示子查询存在返回true,不存在返回false。
由exists引出的子查询,其目标列表达式通常都用“*”表示,因为往往只关心是否返回值,而不关心返回什么值。
使用示例
1、查询如果用户1发布了博文,则列出用户1的用户信息。
select * from `user` u where u.id=1 and exists (select * from `article` a where a.uid=1); +----+----------+------+ | id | username | sex | +----+----------+------+ | 1 | user1 | 1 | +----+----------+------+ 1 row in set (0.00 sec)
2、查询发布过博文的用户信息列表
select * from `user` u where exists (select * from `article` a where a.uid=u.id); +----+----------+------+ | id | username | sex | +----+----------+------+ | 1 | user1 | 1 | +----+----------+------+ 1 row in set (0.00 sec)
3、查询没有下过订单的用户信息列表
select * from `user` u where not exists (select * from `order` o where o.uid=u.id); +----+----------+------+ | id | username | sex | +----+----------+------+ | 2 | user2 | 0 | +----+----------+------+ 1 row in set (0.00 sec)
数据库表参考
数据库表
-- 用户表 CREATE TABLE `user` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `username` varchar(20) DEFAULT NULL, `sex` tinyint(1) unsigned DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `key_username` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- 文章表 CREATE TABLE `article` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `uid` int(11) unsigned NOT NULL, `title` varchar(50) NOT NULL, `content` text NOT NULL, PRIMARY KEY (`id`), KEY `key_title` (`title`), KEY `key_uid` (`uid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; --订单表 CREATE TABLE `order` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `uid` int(11) unsigned NOT NULL, `ordersn` varchar(50) NOT NULL, `price` decimal(10,2) NOT NULL, `status` tinyint(1) unsigned DEFAULT '0', PRIMARY KEY (`id`), KEY `key_ordersn` (`ordersn`), KEY `key_uid` (`uid`), KEY `key_status` (`status`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
相应数据
mysql> select * from user; +----+----------+------+ | id | username | sex | +----+----------+------+ | 1 | user1 | 1 | | 2 | user2 | 0 | +----+----------+------+ 2 rows in set (0.02 sec) mysql> select * from article; +----+-----+-----------+-----------+ | id | uid | title | content | +----+-----+-----------+-----------+ | 1 | 1 | 博文标题1 | 博文内容1 | | 2 | 1 | 博文标题2 | 博文标题2 | +----+-----+-----------+-----------+ 2 rows in set (0.07 sec) mysql> select * from `order`; +----+-----+------------------+-------+--------+ | id | uid | ordersn | price | status | +----+-----+------------------+-------+--------+ | 1 | 1 | 2018011149985556 | 1.25 | 1 | +----+-----+------------------+-------+--------+ 1 row in set (0.00 sec)
原创文章,转载请注明出处:https://www.weizhixi.com/article/75.html