PostgreSQL - 在具有两个不同列的视图上选择

时间:2015-02-16 23:07:19

标签: postgresql select view distinct

我有一个观点,invoices_psn_sw:

CREATE VIEW invoices_psn_sw
AS SELECT invoices.invoice_number, invoices.shipping_tracking_number, product_serial_numbers.product_serial_number, 
    software.license_number
FROM invoices
LEFT OUTER JOIN product_serial_numbers ON invoices.shipping_tracking_number = product_serial_numbers.shipping_tracking_number
LEFT OUTER JOIN software ON invoices.shipping_tracking_number = software.shipping_tracking_number;

发票的密钥是invoice_number。一张发票可以包含许多product_serial_numbers和软件,并且它们与发票上的fkey shipping_tracking_number一起加入。

问题是,输出显示了product_serial_number,license_number等的所有可能组合。

我能做到;

SELECT DISTINCT ON (product_serial_number)

但我需要的是product_serial_number和license_number。

如果我有3个license_numbers和2个product_serial_numbers共享一个shipping_tracking_number,它将显示总共6个记录。我希望它显示尽可能少 - 在这种情况下,3。

额外代码(缩写):

CREATE TABLE Product_Serial_Numbers (
    product_serial_number varchar(32) CONSTRAINT product_serial_number_pkey PRIMARY KEY,
    job_number varchar(32) REFERENCES Jobs(job_number) ON UPDATE CASCADE ON DELETE SET NULL,
    shipping_tracking_number varchar(64) REFERENCES Shipping(tracking_number) ON UPDATE CASCADE ON DELETE SET NULL
);

CREATE TABLE Software (
    license_number varchar(32) CONSTRAINT license_number_pkey PRIMARY KEY,
    job_number varchar(32) REFERENCES Jobs(job_number) ON UPDATE CASCADE ON DELETE SET NULL
);

CREATE RULE invoices_psn_sw_insert
AS ON INSERT TO invoices_psn_sw
DO INSTEAD
(INSERT INTO invoices(invoice_number, shipping_tracking_number)
VALUES (NEW.invoice_number, NEW.shipping_tracking_number);
UPDATE product_serial_numbers SET shipping_tracking_number = NEW.shipping_tracking_number WHERE product_serial_number = NEW.product_serial_number1;
...
UPDATE product_serial_numbers SET shipping_tracking_number = NEW.shipping_tracking_number WHERE product_serial_number = NEW.product_serial_number30;
UPDATE software SET shipping_tracking_number = NEW.shipping_tracking_number WHERE license_number = NEW.sw_license_number1;
...
UPDATE software SET shipping_tracking_number = NEW.shipping_tracking_number WHERE license_number = NEW.sw_license_number10;
);

由于

0 个答案:

没有答案