[英]Converting sub-query to join to create a view
I have a nested SQL query : 我有一个嵌套的SQL查询:
SELECT *
FROM
(
SELECT *
FROM asset_status
ORDER BY session_id DESC
) tmp
GROUP BY asset_id, workflow_element_id
I would like to create a view from this query but MySQL doesn't seem to allow subqueries in views. 我想从这个查询创建一个视图,但MySQL似乎不允许视图中的子查询。 How can convert this to a join? 如何将其转换为连接?
SQL Server does allow sub-queries in views. SQL Server允许在视图中进行子查询。 What you can't do, is SELECT *
and GROUP BY a, b
你不能做的是SELECT *
和GROUP BY a, b
Have you tried... (I'll assume this isn't your whole query so I'll make the minimum possible changes) 你试过......(我假设这不是你的整个查询,所以我会做出最小的改动)
SELECT asset_id, workflow_element_id
FROM
(
SELECT *
FROM asset_status
-- ORDER BY session_id DESC (Removed as innefective in a view)
) tmp
GROUP BY asset_id, workflow_element_id
Also, note that the ORDER BY in the inner query is innefective (and possibly even dis-allowed), as the outer query is then allowed to re-order it (it won't always come back in a different order, but this layout doesn't guarnatee the order you seem to want). 另外,请注意内部查询中的ORDER BY是无效的(甚至可能是不允许的),因为允许外部查询对其进行重新排序(它不会总是以不同的顺序返回,但是这种布局不guarnatee的顺序,你似乎想)。 Even in the outer query, it may cause your results to be order when using the view, but again the optimiser is allowed to re-order the results. 即使在外部查询中,它也可能导致您在使用视图时对结果进行排序,但同样允许优化器重新排序结果。 Unless the ORDER BY is in the query using the view, the order is never absolutely guaranteed ... 除非ORDER BY在使用视图的查询中,否则订单永远不会绝对保证 ...
SELECT * FROM view ORDER BY x
Finally, you tagged this as a LEFT JOIN question. 最后,您将此标记为LEFT JOIN问题。 If you have a more complete example of the code, I'm sure someone will suggest an alternative layout. 如果你有一个更完整的代码示例,我相信有人会建议一个替代布局。 But I'm off out for a few days now. 但是我现在已经退出了几天。 Good luck! 祝好运! :) :)
There is no need for subquery since the inner order by is not guaranteed to be used at all. 不需要子查询,因为根本不保证使用内部顺序。 You can write: 你可以写:
SELECT DISTINCT asset_id, workflow_element_id
FROM asset_status
If you need to order by session_id
you would have to include it in an aggregate, max
for example. 如果您需要按session_id
排序,则必须将其包含在聚合中,例如max
。 (or in the group by) (或在小组中)
SELECT asset_id, workflow_element_id
FROM asset_status
GROUP BY asset_id, workflow_element_id
ORDER BY MAX(session_id) DESC
According to the MySQL reference manual , you can create views that use sub-queries, but not in the From clause. 根据MySQL参考手册 ,您可以创建使用子查询的视图,但不能在From子句中创建。
Therefore, I think you need to create your view like the following: 因此,我认为您需要创建如下视图:
select a.*
from asset_status a
join (select asset_id, workflow_element_id, MAX(session_id) session_id
from asset_status
group by asset_id, workflow_element_id) sq
on a.session_id = sq.session_id
However, it probably won't perform as well as your original query. 但是,它可能无法执行原始查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.