开发者

Referring to other SQL scripts from a SQL script?

I'm currently converting MS access queries to SQL queries and noticed that in the access query it appears to be joining another query to other tables. So I looked around and it seems like that query pretty much makes the query look cleaner without needing to have all sorts of subqueries in the same script

Something like

FROM [query name] INNER JOIN [som开发者_JAVA技巧e other table]

Is there something like this in SQL?


You are probably looking for VIEWS.

A view is basically a stored version of a SELECT query. It allows you to reference the result set without rewriting the query every time.


You can create a VIEW as a query, then reference the view in another query.

CREATE VIEW <viewname> AS <SELECT STATEMENT>

then

SELECT * FROM <viewname> INNER JOIN <other table>


Yes. They are called views.

You can create a view like

CREATE VIEW vw_some_query AS
SELECT * FROM
 table_a LEFT INNER JOIN table_b ON table_a.id = table_b.id2

then you can write a select like:

SELECT * FROM vw_some_query LEFT INNER JOIN table_c ON vw_some_query.id = table_c.id3


Is there something like this in SQL?

Yes. In SQL you would probably use the WITH clause:

WITH someData AS
(
  select a.col1, b.col2
  from tableA a join tableB b
  on (a.someKey = b.someKey)
),
...
select data1.col1, data1.col2, data2.col3
from someData data1 join tableC data2
on (data1.col1 = data2.anotherKey)
where ...

Views are ok too, but another db object to keep track of, and if using a materialized view, need to worry about refreshing snapshot table, etc. My suggestion is to use WITH along with plenty of comments where possible.

EDIT: If you find yourself asking the same question of the db over and over, then a view (or mat view) would be more appropriate. But otherwise, keep logic in the query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜