CREATE TABLE facttable_stat_fta4 (
    berechnungsart      VARCHAR(64),
    einheit             VARCHAR(64)
);

INSERT INTO facttable_stat_fta4
SELECT (CASE WHEN r < 0.48 THEN 'n' ELSE 'm' END),
       (CASE WHEN r < 0.48 THEN 'EUR' ELSE 'kg' END)
  FROM (SELECT random() AS r FROM generate_series(1,10000000)) foo;

CREATE INDEX facttable_stat_fta4_berechnungsart_idx ON facttable_stat_fta4 (berechnungsart);
CREATE INDEX facttable_stat_fta4_einheit_idx ON facttable_stat_fta4 (einheit);

ANALYZE facttable_stat_fta4;


CREATE TABLE term (
    facttablename          VARCHAR(64),
    columnname             VARCHAR(64),
    term                   VARCHAR(64)
);

INSERT INTO term
SELECT md5(random()::text),
       md5(random()::text),
       substr(md5(random()::text),0,8)
FROM   generate_series(1,1000000) s(i);

INSERT INTO term VALUES ('facttable_stat_fta4', 'berechnungsart', 'n');
INSERT INTO term VALUES ('facttable_stat_fta4', 'berechnungsart', 'm');
INSERT INTO term VALUES ('facttable_stat_fta4', 'einheit', 'kg');
INSERT INTO term VALUES ('facttable_stat_fta4', 'einheit', 'EUR');

CREATE INDEX term_facttablename_columnname_idx ON term (facttablename, columnname);
CREATE INDEX term_term_idx ON term (term);

ANALYZE term;

EXPLAIN
 SELECT facttablename, columnname, term
   FROM term t WHERE facttablename='facttable_stat_fta4' AND columnname='einheit'
                 AND exists (SELECT 1 FROM facttable_stat_fta4 f WHERE f.einheit=t.term );
        
EXPLAIN
 SELECT facttablename, columnname, term
   FROM term t WHERE facttablename='facttable_stat_fta4' AND columnname='berechnungsart'
                 AND exists (SELECT 1 FROM facttable_stat_fta4 f WHERE f.berechnungsart=t.term );
