选择在复杂的pl / pgsql查询中不起作用的独特对象

时间:2018-12-02 18:10:09

标签: postgresql group-by sql-order-by distinct plpgsql

我在pl / pgsql函数中有此查询。我正在使用PostgreSQL10。

FOR firstrecord IN 
EXECUTE format( 

 'SELECT  vans.id as vid, adidas.id as aid, 
 vans.color, adidas.color, vans.type, adidas.type 
 FROM shoes 
 FULL JOIN adidas ON shoes.id = adidas.id 
 FULL JOIN shoes ON shoes.id=vans.id
 WHERE  adidas.code = 607 and vans.code = 304 '  )              

 USING acode , vcode 

END LOOP;

这可行,但是我想对SELECT DISTINCT强制执行vans.id并且  adidas.id。 这是我最近的

FOR firstrecord IN 
EXECUTE format( 

 'SELECT DISTINCT ON  (adidas.id)  vans.id as vid, adidas.id as aid, 
 vans.color, adidas.color, vans.type, adidas.type 
 FROM shoes 
 FULL JOIN adidas ON shoes.id = adidas.id 
 FULL JOIN shoes ON shoes.id=vans.id
 WHERE  adidas.code = 607 and vans.code = 304 
 ORDER BY adidas.id,vans.id'  )              

 USING acode , vcode 

END LOOP;

如果我尝试执行类似SELECT DISTINCT ON (adidas.id, vans.id)的操作,则DISTINCT无效,那么结果将重复。

如果我执行SELECT DISTINCT vans.id as vid, adidas.id as aid,但DISTINCT仍然不起作用,结果将重复。

该如何解决?

谢谢

1 个答案:

答案 0 :(得分:1)

正如您现在所看到的,如果使用DISTINCT ON(expression1,expression2),它将把这两个表达式的所有组合计为不同的值,包括当一个为NULL时则与任何非NULL值都不同。似乎您只需要一个表达式来考虑两个表中的ID。您可以使用合并功能来获得它,如下所示:

SELECT DISTINCT ON  ( coalesce(adidas.id, vans.id))  vans.id as vid, adidas.id as aid, 
vans.color, adidas.color, vans.type, adidas.type 
FROM shoes 
FULL JOIN adidas ON shoes.id = adidas.id 
FULL JOIN vans ON shoes.id = vans.id
WHERE  adidas.code = 607 and vans.code = 304 
ORDER BY coalesce(adidas.id, vans.id)

在这种情况下可行,因为如果两者均为非NULL,则它们应该彼此匹配;如果二者为NULL,则结盟语句将返回非NULL值。