Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何从多个表中获取匹配的记录_Sql_Postgresql - Fatal编程技术网

Sql 如何从多个表中获取匹配的记录

Sql 如何从多个表中获取匹配的记录,sql,postgresql,Sql,Postgresql,如何从至少在两个表中匹配的表中获取记录?例如,具有相同名称的所有帐户。可以有很多桌子。PostgreSQL用作数据库 在第一个表中,有: id name -------- 11 acc1 12 acc4 13 acc5 14 acc9 15 acc10 16 acc1 17 acc1 18 acc4 19 acc10 id name -------- 21 acc4 22 acc6 23 acc8 24 acc10 id nam

如何从至少在两个表中匹配的表中获取记录?例如,具有相同名称的所有帐户。可以有很多桌子。PostgreSQL用作数据库

在第一个表中,有:

id   name
--------
11   acc1
12   acc4
13   acc5
14   acc9
15   acc10
16   acc1
17   acc1
18   acc4
19   acc10
id   name
--------
21   acc4
22   acc6
23   acc8
24   acc10
id   name
--------
31   acc1
32   acc7
33   acc9
34   acc8
35   acc10
第二个表中有:

id   name
--------
11   acc1
12   acc4
13   acc5
14   acc9
15   acc10
16   acc1
17   acc1
18   acc4
19   acc10
id   name
--------
21   acc4
22   acc6
23   acc8
24   acc10
id   name
--------
31   acc1
32   acc7
33   acc9
34   acc8
35   acc10
第三个表中有:

id   name
--------
11   acc1
12   acc4
13   acc5
14   acc9
15   acc10
16   acc1
17   acc1
18   acc4
19   acc10
id   name
--------
21   acc4
22   acc6
23   acc8
24   acc10
id   name
--------
31   acc1
32   acc7
33   acc9
34   acc8
35   acc10
结果应该是:

id-1  id-2  id-3
----------------
11    null  31
12    21    null
14    null  33
15    24    35
null  23    34

每个列中的ID只能使用一次,并且条件可能更复杂,例如,记录应该由两个字段匹配。

您似乎想要一个
完全联接:

select t1.id, t2.id, t3.id
from t1 full join
     t2
     using (name) full join
     t3
     using (name)
where ( (t1.id is not null)::int +
        (t2.id is not null)::int +
        (t3.id is not null)::int
      ) >= 2;
如果您不想要副本,则可以执行以下操作:

select t1.id, t2.id, t3.id
from (select name, min(id) as id from t1) t1 full join
     (select name, min(id) as id from t2) t2
     using (name) full join
     (select name, min(id) as id from t3) t3
     using (name)
where ( (t1.id is not null)::int +
        (t2.id is not null)::int +
        (t3.id is not null)::int
      ) >= 2;

获取所有名称,并为每个名称保留其出现的表。然后查看哪些名称具有2个以上的关联表。或者,如果每个名称出现的表不重要,只需为每个名称保留一个计数器。您能解释一下阻止19/24/35的条件吗?@GordonLinoff 24和35已在结果的第4行中使用