本文介绍了除了声明性语言外,SQL是一种功能性语言吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么是或为什么不是?

解决方案

SQL 作为一种声明性语言,就你告诉你想得到什么和 SQL 引擎决定<$ c $但是, SQL 在集合上操作,并且结果如下: 。

函数可以是 Oracle , SQL Server 和 PostgreSQL

可以说, SQL 是函数式语言,只要函数将一个集合作为它的输入并产生一组作为它的输出。

也就是说,你可以写这样的东西:

  SELECT * 
FROM mytable t
JOIN myfunction(x)f
ON f.col1 = t.col2



,甚至是这个:

  SELECT * 
FROM mytable t
CROSS APPLY
myfunction(t.col2)f

(在 SQL Server

或者这个:

$ p $ SELECT t。*, myfunction(t.col2)
FROM mytable t

(在 PostgreSQL )



尽管这不是 SQL标准的一部分。 p>

就像 C ++ 编译器试图找到一个最佳方式来乘以两个 float s(用简单的代数), SQL 优化器试图找到一个最优方法来乘两组(用关系代数的方式)。



在 C ++ 中,您只需编写 a * b 并依靠编译器为此生成一个最佳程序集。



在 SQL 中,您编写 SELECT * FROM一个NATURAL JOIN b 并依赖于优化器。



然而,所有 SQL ' (没有双关语意思),大多数真正的优化器只能做非常基本的查询重写。



说,我知道没有优化器可以使用SA我为这个查询的高效计划:

pre code> SELECT t1.id,t1.value,SUM(t2.value)
FROM mytable t1
JOIN mytable t2
ON t2.id< = t1.id
GROUP BY
t1.id,t1.value

$ b

  SELECT id,value,SUM(t1.value)OVER(ORDER BY id)
FROM mytable

,更不用说更复杂的查询了。



这就是为什么你仍然需要制定你的查询,以便他们使用一个有效的计划(同时产生相同的结果),从而使得 SQL 少于一种声明性语言。



我最近在我的博客中发表了这篇文章:




Why yes or why not?

解决方案

SQL was designed as a declarative language, in sense that you tell what you want to get and the SQL engine decides how.

However, SQL operates on sets, and the results of the functions can be first class sets in Oracle, SQL Server and PostgreSQL.

One can say that SQL is functional language, as long as a function takes a set as its input and produces a set as its output.

That is, you can write something like this:

SELECT  *
FROM    mytable t
JOIN    myfunction(x) f
ON      f.col1 = t.col2

, or even this:

SELECT  *
FROM    mytable t
CROSS APPLY
        myfunction(t.col2) f

(in SQL Server)

or this:

SELECT  t.*, myfunction(t.col2)
FROM    mytable t

(in PostgreSQL)

This is not a part of SQL standard, though.

Just like a C++ compiler tries to find an optimal way to multiply two floats (in terms of plain algebra), SQL optimizer tries to find an optimal ways to multiply two sets (in terms of relational algebra).

In C++, you just write a * b and rely on compiler to generate an optimal assembly for this.

In SQL, you write SELECT * FROM a NATURAL JOIN b and rely on optimizer.

However, with all SQL's declared declarativity (no pun intended), most real optimizers are able to do only very basic query rewrites.

Say, no optimizer I'm aware of is able to use same efficient plan for this query:

SELECT  t1.id, t1.value, SUM(t2.value)
FROM    mytable t1
JOIN    mytable t2
ON      t2.id <= t1.id
GROUP BY
        t1.id, t1.value

and for this one:

SELECT  id, value, SUM(t1.value) OVER (ORDER BY id)
FROM    mytable

, to say nothing of more complex queries.

That's why you still need to formulate your queries so that they use an efficient plan (while still producing the same result), thus making SQL quite a bit less of a declarative language.

I recently made post in my blog on this:

这篇关于除了声明性语言外,SQL是一种功能性语言吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 15:48