9.3 og derover:lateral forespørgsel
I PostgreSQL 9.3 eller nyere brug en implicit lateral forespørgsel:
SELECT f.* FROM things t, some_function(t.thing_id) f;
Foretrække denne formulering til alle nye forespørgsler . Ovenstående er standardformuleringen .
Det fungerer også korrekt med funktioner, der RETURNS TABLE
eller RETURNS SETOF RECORD
samt funktioner med ud-parametre, der RETURNS RECORD
.
Det er en forkortelse for:
SELECT f.*
FROM things t
CROSS JOIN LATERAL some_function(t.thing_id) f;
Pre-9.3:udvidelse af jokertegn (med omhu)
Tidligere versioner forårsager multiple-evaluering af some_function
, gør ikke virker, hvis some_function
returnerer et sæt, brug ikke dette :
SELECT (some_function(thing_id)).* FROM things;
Tidligere versioner undgår multiple-evaluering af some_function
ved at bruge et andet lag af indirektion. Brug kun dette, hvis du skal understøtte ret gamle PostgreSQL-versioner.
SELECT (f).*
FROM (
SELECT some_function(thing_id) f
FROM things
) sub(f);
Demo:
Opsætning:
CREATE FUNCTION some_function(i IN integer, x OUT integer, y OUT text, z OUT text) RETURNS record LANGUAGE plpgsql AS $$
BEGIN
RAISE NOTICE 'evaluated with %',i;
x := i;
y := i::text;
z := 'dummy';
RETURN;
END;
$$;
create table things(thing_id integer);
insert into things(thing_id) values (1),(2),(3);
testkørsel:
demo=> SELECT f.* FROM things t, some_function(t.thing_id) f;
NOTICE: evaluated with 1
NOTICE: evaluated with 2
NOTICE: evaluated with 3
x | y | z
---+---+-------
1 | 1 | dummy
2 | 2 | dummy
3 | 3 | dummy
(3 rows)
demo=> SELECT (some_function(thing_id)).* FROM things;
NOTICE: evaluated with 1
NOTICE: evaluated with 1
NOTICE: evaluated with 1
NOTICE: evaluated with 2
NOTICE: evaluated with 2
NOTICE: evaluated with 2
NOTICE: evaluated with 3
NOTICE: evaluated with 3
NOTICE: evaluated with 3
x | y | z
---+---+-------
1 | 1 | dummy
2 | 2 | dummy
3 | 3 | dummy
(3 rows)
demo=> SELECT (f).*
FROM (
SELECT some_function(thing_id) f
FROM things
) sub(f);
NOTICE: evaluated with 1
NOTICE: evaluated with 2
NOTICE: evaluated with 3
x | y | z
---+---+-------
1 | 1 | dummy
2 | 2 | dummy
3 | 3 | dummy
(3 rows)