您的位置:首页 > 数据库 > Oracle

ORACLE查询语句简单实例

2013-09-11 08:36 363 查看
需求:

假如有一张书目表,字段为id,name,count(库存)

现要插入一条新纪录,如果数据库没有这条纪录,插入

若已经存在,则更新库存。

解决方法:mysql 的 on duplicate key update 语法。

下面给出解决过程。

创建测试数据库

mysql> CREATE DATABASE `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

Query OK, 1 row affected (0.14 sec)

mysql> use test;

Database changed

创建测试数据表

mysql> CREATE TABLE IF NOT EXISTS `books` (

-> `id` int(10) unsigned not null auto_increment,

-> `name` varchar(50) not null,

-> `count` smallint(5) unsigned not null default '0',

-> primary key(`id`),

-> unique key(`name`)

-> ) ENGINE=INNODB DEFAULT CHARSET=utf8 ;

Query OK, 0 rows affected (0.79 sec)

查看索引信息

mysql> show index from books;

+-------+------------+----------+--------------+-------------+-----------+-------------+----------| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |

+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+

| books | 0 | PRIMARY | 1 | id | A | 0 | NULL | NULL | | BTREE | |

| books | 0 | name | 1 | name | A | 0 | NULL | NULL | | BTREE | |

+-------+------------+----------+--------------+-------------+-----------+-------------+----------2 rows in set (0.00 sec)

插入第一条测试数据

mysql> INSERT INTO `books` VALUES ('','windows',5);

Query OK, 1 row affected, 1 warning (0.04 sec)

查看数据

mysql> select * from books;

+----+---------+-------+

| id | name | count |

+----+---------+-------+

| 1 | windows | 5 |

+----+---------+-------+

1 row in set (0.00 sec)

再次插入windows这本书

mysql> INSERT INTO `books` VALUES ('','windows',1)

-> ON DUPLICATE KEY UPDATE `count` = `count` + VALUES(`COUNT`);

Query OK, 2 rows affected, 1 warning (0.12 sec)

再来查看数据

mysql> select * from books;

+----+---------+-------+

| id | name | count |

+----+---------+-------+

| 1 | windows | 6 |

+----+---------+-------+

1 row in set (0.00 sec)

大功告成,相当之好用!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: