Use mysql view

View is a virtual table by one or more base table (or view) is generated, the database is stored in a definition of a view, corresponding data is located in the physical data table.

Use the view can sometimes simplify user operations, especially when you need the associated multi-table queries, do not care about the internal structure view of the query, only focus on the data acquired ask

Syntax is as follows:

CREATE VIEW <view name> AS <SELECT statement>

The syntax is described below.

  • <视图名>: Specifies the name of the view. The name must be unique in the database, not the same name as other tables or views.
  • <SELECT语句>: Specifies the SELECT statement to create a view that can be used to query multiple underlying table or source view.

1, ready to work

Orders table:

DROP TABLE IF EXISTS `t_order`;
CREATE TABLE `t_order` (
`id`  int(11) NOT NULL AUTO_INCREMENT ,
`user_id`  int(11) NOT NULL ,
`order_time`  int(10) NOT NULL ,
`fee`  int(11) NOT NULL ,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci;

Order Details table:

DROP TABLE IF EXISTS `t_order_detail`;
CREATE TABLE `t_order_detail` (
`id`  int(11) NOT NULL AUTO_INCREMENT ,
`goods_id`  varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`count`  int(11) NOT NULL ,
`order_id`  int(11) NOT NULL ,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci;

Commodity table:

DROP TABLE IF EXISTS `t_goods`;
CREATE TABLE `t_goods` (
`id`  int(11) NOT NULL AUTO_INCREMENT ,
`good_name`  varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`price`  int(11) NOT NULL ,
`stock`  int(11) NOT NULL ,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci;

Initialization test data:

INSERT INTO `t_goods` VALUES ('1', 'a', '12', '100'), ('2', 'b', '1', '100');
INSERT INTO `t_order` VALUES ('1', '1', '20190912', '1000000');
INSERT INTO `t_order_detail` VALUES ('1', '1', '10', '1'), ('2', '2', '5', '1');

2, create a view

CREATE VIEW order_detail_2 (id, user_id, goods_name, goods_price, count, fee) AS SELECT
    o.id,
    o.user_id,
    tg.good_name,
    tg.price,
    tod.count,
    (tg.price * tod.count)
FROM
    t_order o
RIGHT JOIN t_order_detail tod ON o.id = tod.order_id
RIGHT JOIN t_goods tg ON tod.goods_id = tg.id
WHERE o.id = 1;

This view is detailed information query order number 1, after which you can use to directly view the query, and the query process on the basis of the same table

SELECT * from order_detail;

 

Guess you like

Origin www.cnblogs.com/kingsonfu/p/11511115.html