SQL在LEFT OUTER JOIN上只获得一个最大id字段

时间:2016-07-28 14:11:39

标签: sql postgresql

如何将用户表的值与表的通知的最大值进行比较?

SELECT "vkId" AS "id"
FROM "user" AS "user" 

LEFT OUTER JOIN "notification" ON "notification"."userId" = "user"."vkId"

WHERE (
"user"."vipEnd" < 1469714507 
AND "user"."vipEnd" > 1469710907
) AND (
(
    "notification"."type" = 4
    AND 

    "notification"."expiresVipDate" < 1469710907
) 
OR "notification"."id" IS NULL
)


LIMIT '100';

1 个答案:

答案 0 :(得分:0)

您可以使用DISTINCT ON,按expiresVipDate DESC排序:

SELECT DISTINCT ON (u."vkId") u."vkId" AS id, n.*
FROM "user" AS u
LEFT JOIN notification n ON (n."userId" = u."vkId" AND
                             n.type = 4 AND
                             n."expiresVipDate" < 1469710907)
WHERE u."vipEnd" < 1469714507 AND u."vipEnd" > 1469710907
ORDER BY u."vkId", n."expiresVipDate" DESC
LIMIT 100;