根据它在另一个表psql中的可用性来排序一个表的结果

时间:2018-02-14 08:13:33

标签: sql postgresql psql

我有5张桌子A,A1,A2,A3,A4。 A与其余4个表具有外键关系。

我首先要检查A1中的可用性,然后再检查A2中的可用性,依此类推。

因此,结果应按A1,A2,A3,A4中的可用性顺序显示。

select * from A as main
order by (select abc from A1 where main.abc = A1.abc), (select abc from A2 where main.abc = A2.abc), (select abc from A3 where main.abc = A3.abc), (select abc from A4 where main.abc = A4.abc)

如果A表中有10条记录,那么我想要结果中的所有10条记录,但是这些记录应按A1,A2,A3和A4中的可用性排序 我们将不胜感激。

3 个答案:

答案 0 :(得分:2)

使用LEFT JOINCOALESCE

select distinct A.* 
from A
LEFT JOIN A1 ON A.abc = A1.abc
LEFT JOIN A2 ON A.abc = A2.abc
LEFT JOIN A3 ON A.abc = A3.abc
LEFT JOIN A4 ON A.abc = A4.abc
ORDER BY COALESCE(A1.abc,A2.abc,A3.abc,A4.abc)

然而,它没有多大意义。排序将根据abc值。如果您打算根据A1 - A4中的某个值进行订购,请在abc中使用它而不是COALESCE

如果您希望行首先在A1中,那么您可以使用||根据A1-A4存在执行排序(如果abc属性为varchar

select distinct A.* 
from A
LEFT JOIN A1 ON A.abc = A1.abc
LEFT JOIN A2 ON A.abc = A2.abc
LEFT JOIN A3 ON A.abc = A3.abc
LEFT JOIN A4 ON A.abc = A4.abc
ORDER BY COALESCE('a' || A1.abc, 'b' || A2.abc, 'c' || A3.abc, 'd' || A4.abc)

答案 1 :(得分:1)

您可以按EXISTance排序:

-- sample data
CREATE TABLE a ( abc integer not null primary key);
INSERT INTO a(abc)
select generate_series(1,25);

CREATE TABLE a2 AS select * FROM a where abc %2 = 0;
CREATE TABLE a3 AS select * FROM a where abc %3 = 0;
CREATE TABLE a5 AS select * FROM a where abc %5 = 0;
CREATE TABLE a7 AS select * FROM a where abc %7 = 0;

ALTER TABLE a2 ADD primary key(abc);
ALTER TABLE a3 ADD primary key(abc);
ALTER TABLE a5 ADD primary key(abc);
ALTER TABLE a7 ADD primary key(abc);

-- Query


select * from a
ORDER BY exists (select * from a2 where abc=a.abc) desc
        , exists (select * from a3 where abc=a.abc) desc
        , exists (select * from a5 where abc=a.abc) desc
        , exists (select * from a7 where abc=a.abc) desc
        , a.abc -- tie-breaker
     ;

结果:

CREATE TABLE
INSERT 0 25
SELECT 12
SELECT 8
SELECT 5
SELECT 3
ALTER TABLE
ALTER TABLE
ALTER TABLE
ALTER TABLE
 abc 
-----
   6
  12
  18
  24
  10
  20
  14
   2
   4
   8
  16
  22
  15
  21
   3
   9
   5
  25
   7
   1
  11
  13
  17
  19
  23
(25 rows)

答案 2 :(得分:0)

使用COALESCE

SELECT A.* 
FROM A LEFT JOIN A1 ON A.ID = A1.ID
LEFT JOIN A2 ON A.ID = A2.ID 
LEFT JOIN A3 ON A.ID = A3.ID 
LEFT JOIN A4 ON A.ID = A4.ID 
ORDER BY COALESCE(A1.ID ,A2.ID ,A3.ID ,A4.ID )