从包含多个子查询的Select语句创建视图

时间:2014-09-12 22:47:48

标签: mysql view

SELECT z.`id`, z.`ukupno` ,s.uk, (ukupno-uk) as r from zbirni z
 join 
(SELECT k.`iddzid`,  (sum(kolicina*cjena)) as uk FROM   kasa k   join kasa_detalji d on d.idd=k.id group by  iddzid) as s 
on s.iddzid=z.id
 where (ukupno-uk)>0

但我有错误 脚本行:1视图的SELECT包含FROM子句中的子查询

1 个答案:

答案 0 :(得分:0)

您可以使用连接重写查询以避免使用子查询和Mysql视图的限制

SELECT 
z.`id`, 
z.`ukupno` ,
SUM(kolicina * cjena) uk, 
(ukupno - SUM(kolicina * cjena)) AS r 
FROM zbirni z
 JOIN kasa k  ON(z.id=k.`iddzid`)
 JOIN kasa_detalji d ON (d.idd=k.id)
GROUP BY z.`id`
HAVING r > 0

或为每个子查询创建视图,并在您的视图中使用它,如

CREATE VIEW calc_sum
AS 
SELECT k.`iddzid`,  
SUM(kolicina*cjena) AS uk FROM   kasa k  
JOIN kasa_detalji d ON d.idd=k.id 
GROUP BY  iddzid

在查询中使用calc_sum视图

CREATE VIEW your_view_name
SELECT 
z.`id`, 
z.`ukupno` ,
s.uk, 
(ukupno-uk) AS r 
FROM zbirni z
 JOIN  calc_sum AS s ON s.iddzid=z.id
WHERE (ukupno-uk)>0