我在MySQL中创建物化视图,以便在从一堆其他表(一次一个产品)查询数据时减少服务器负载。我的简化代码如下:
DROP TABLE IF EXISTS `db`.`view_stock`;
CREATE TABLE IF NOT EXISTS `db`.`view_stock` (
SELECT A.title, on_order,(stock-sales) AS 'Stock' FROM
(SELECT SUM(`bought_products`.`qty`) AS 'on_order'
,`bought_products`.product_id, title FROM
`bought_products` GROUP BY product_id)
A,
(SELECT SUM(num) AS `stock`,product_id FROM plugins__stock GROUP BY
product_id)
B,
(SELECT SUM(`bought_products`.`qty`) AS `sales`
,`bought_products`.`product_id` FROM `storage__bought_products` JOIN
`plugins__orders` WHERE `bought_products`.`order_id` =
`plugins__orders`.`id` AND
((`plugins__orders`.`status` = 'paid') OR
(`plugins__orders`.`status` = 'shipped'))
GROUP BY product_id)
C
WHERE B.product_id = A.product_id AND C.product_id = A.product_id ORDER BY on_order)
当我自己运行查询时,它会工作并按预期返回数据。但是,当我尝试在上面的上下文中创建表时,我收到以下错误:Unrecognized data type. (near 'A')
此错误在查询开头突出显示,其中' A'首先提到(靠近' A.title')。
下面是样本结果:
Title on_order Stock
'Widget' 6 15
'Gadget' 3 10
我尝试过使用其他方法来声明表格,但似乎没有任何效果。有没有人有任何想法?
bought_products
的表格结构为:
CREATE TABLE `bought_products` (
`id` bigint(20) NOT NULL,
`order_id` bigint(20) NOT NULL,
`product_id` bigint(20) NOT NULL,
`qty` int(11) NOT NULL,
`stock_count` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
)
plugins__stock
的表格结构为:
CREATE TABLE `plugins__stock` (
`id` bigint(20) NOT NULL,
`product_id` bigint(20) NOT NULL,
`num` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
plugins__orders
的表格结构为:
CREATE TABLE `plugins__orders` (
`id` bigint(20) NOT NULL,
`name` tinytext NOT NULL,
...
`status` enum('open','paid','shipped','deleted')
)
这些显然缩短了以保持帖子长度短。