自定义函数 与 视图 在使用上有什么区别?
测试环境:
PostgreSQL
测试用例:
CREATE TABLE a (
aid serial PRIMARY KEY,
name varchar(20)
);
CREATE TABLE b (
bid serial PRIMARY KEY,
name varchar(20)
);
CREATE TABLE ab (
abid serial PRIMARY KEY,
aid serial REFERENCES a(aid),
bid serial REFERENCES b(bid)
);
CREATE VIEW v_ab
AS
SELECT a.name AS "aname",
b.name AS "bname",
ab.abid AS "abid"
FROM a, b, ab
WHERE a.aid = ab.aid
AND b.bid = ab.bid;
CREATE FUNCTION f_ab(int)
RETURNS TABLE(aname varchar, bname varchar) AS $$
SELECT a.name AS "aname",
b.name AS "bname"
FROM a, b, ab
WHERE a.aid = ab.aid
AND b.bid = ab.bid
AND ab.abid = $1
$$ LANGUAGE SQL;
INSERT INTO a VALUES (1, 'a');
INSERT INTO b VALUES (2, 'b');
INSERT INTO ab VALUES (12, 1, 2);
这两篇文章把我搞糊涂了:
慎用自定义函数
和
通过自定义函数提高服务器性能
抱着"存在即合理"的想法,我想知道到底什么时候该使用自定义函数?
另外,当数据量较大时,下面这两条语句执行效率上有区别吗?
SELECT aname, bname FROM v_ab WHERE abid = 12;
SELECT aname, bname FROM f_ab(12);
翠香poi
11 years, 10 months ago