使用Rails迁移(但并不重要)。我试图在这里创建一个视图,但我得到了
Mysql2::Error: View's SELECT contains a subquery in the FROM clause:
CREATE VIEW `lanciao` AS
当我尝试这个时:
create view lanciao as
select
subtime(payment.created_at, '0 5:0:0') as transaction_date,
`order_item`.total_quantity,
payment.amount as amount,
`order`.payment_type
from payments payment
join orders `order` on `order`.id = payment.order_id
left join donation_items donation on donation.order_id = `order`.id
inner join (
select order_id, sum(quantity) total_quantity
from order_items
group by order_id
) `order_item` on `order`.id = `order_item`.order_id
where payment.payment_state in ('settled', 'completed', 'captured', 'authorized', 'approved')
and `order`.fixed_order_id is null
如果没有create view lanciao
,我可以将select
块运行到最后。我试图重构这个,但无法让它发挥作用。我该如何解决这个问题?
我也知道将它分成不同的观点并互相参考,但我不会喜欢这种方式。
答案 0 :(得分:0)
在MySQL 5.7.7之前,SELECT语句不能在FROM子句中包含子查询。
如果您可以升级到MySQL 5.7.7+,那么您应该可以完全按照自己的意愿去做。
否则,您可能想尝试创建子查询的视图,然后在FROM
中使用该视图。
所以你的SQL可能看起来像:
create view subquery_view as
select order_id, sum(quantity) total_quantity
from order_items
group by order_id
create view lanciao as
select
subtime(payment.created_at, '0 5:0:0') as transaction_date,
`order_item`.total_quantity,
payment.amount as amount,
`order`.payment_type
from payments payment
join orders `order` on `order`.id = payment.order_id
left join donation_items donation on donation.order_id = `order`.id
inner join subquery_view as `order_item` on `order`.id = `order_item`.order_id
where payment.payment_state in ('settled', 'completed', 'captured', 'authorized', 'approved')
and `order`.fixed_order_id is null
请注意,将视图嵌套在彼此内部可能会导致性能问题,但我不知道另一种方法。