繁体   English   中英

使用子查询连接表

[英]Using a subquery to JOIN a table

我有一个起始表,它来自一个查询:

CREATE TABLE my_base 
(
    the_id varchar(6) NOT NULL, 
    the_pay int NOT NULL, 
    the_name varchar(10) NOT NULL
)

INSERT INTO my_base
VALUES ('LMUS01', '2000', 'JOE'), 
       ('LMUS02', '1500', 'JACK')

还有一个债务数据“my_table”:

CREATE TABLE my_table 
(
    the_debt_id varchar(6) NOT NULL, 
    the_debt_amount int NOT NULL, 
    the_debt_date date NOT NULL
)

INSERT INTO my_table
VALUES ('LMUS01', '180', '2/12/2019'), 
       ('LMUS01', '200', '2/11/2019'), 
       ('LMUS01', '300', '2/13/2019'), 
       ('LMUS02', '100', '2/10/2019'), 
       ('LMUS02', '150', '2/12/2019')

我想要的查询是“my_base”中的所有记录都连接到“my_table”中变量“the_debt_date”的最小值:

'LMUS01','2000','JOE','200','2/11/2019'
'LMUS02','1500','JACK','100','2/10/2019' 

当我在“my_table”中一一执行时,我使用以下查询:

SELECT the_debt_amount, the_debt_date FROM my_table 
WHERE the_debt_id = 'LMUS01' 
AND the_debt_date = (select min(the_debt_date) 
FROM my_table WHERE the_debt_id = 'LMUS01')

但我想要来自“my_base”的所有记录。 我试过:

SELECT * FROM my_base 
LEFT JOIN my_table ON the_debt_id = the_id WHERE the_id = the_debt_id 
AND the_debt_date = (select min(the_debt_date) FROM my_table WHERE the_id = the_debt_id)

但它发送一个错误。 任何帮助将不胜感激。

distinct on使用distinct on

SELECT DISTINCT ON (b.the_id) b.*, t.*
FROM my_base b LEFT JOIN
     my_table t
     ON t.the_debt_id = b.the_id 
ORDER BY b.the_id, t.the_debt_date asc;

WHERE子句撤消外连接。 但无论如何都不需要。

让我们试试这个,它在 postgres 中对我有用

SELECT mb.the_id, mb.the_pay, mb.the_name, mt.the_debt_amount, mt.the_debt_date FROM my_base mb
           inner join  my_table mt
           on mb.the_id = mt.the_debt_id
    AND mt.the_debt_date = (select min(the_debt_date)
    FROM my_table WHERE the_debt_id = mt.the_debt_id);

您在 my_base 中有两条记录...

SELECT * 
FROM my_base 
LEFT JOIN my_table ON the_debt_id = the_id
WHERE the_id = the_debt_id 
AND the_debt_date = (select min(the_debt_date) 
                     FROM my_table 
                     WHERE the_id = the_debt_id)

显示两个记录,但包括冗余字段。 消除 * 并包含对您需要的特定字段的引用。

SELECT my_base.the_id 
       , my_base.the_pay 
       , my_base.the_name 
       , my_table.the_debt_amount 
       , my_table.the_debt_date 
FROM my_base 
LEFT JOIN my_table ON the_debt_id = the_id
WHERE the_id = the_debt_id 
AND the_debt_date = (select min(the_debt_date) 
                     FROM my_table 
                     WHERE the_id = the_debt_id)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM