0

我正在使用 postresql,但我真的不擅长构建 sql 查询。我有这个查询,它的工作原理:

SELECT handhistories FROM handhistories 
JOIN pokerhands using (pokerhand_id)  
JOIN gametypes using (gametype_id)
RIGHT OUTER JOIN playerhandscashkeycolumns using (pokerhand_id)
     WHERE pokerhands.site_id=0  
     AND pokerhands.numberofplayers>=5 and  pokerhands.numberofplayers<=7
     AND (bigblind = 2 OR bigblind = 4 )
     AND player_id in 
        (SELECT player_id FROM playerhandscashkeycolumns GROUP BY player_id
         HAVING AVG(case didvpip when true then 100::real else 0 end) <= 20 )

但我也想限制底部的最后一个“拥有”,所以它会是这样的,但它当然不起作用。

SELECT handhistories FROM handhistories 
JOIN pokerhands using (pokerhand_id)  
JOIN gametypes using (gametype_id)
RIGHT OUTER JOIN playerhandscashkeycolumns using (pokerhand_id)
       WHERE pokerhands.site_id=0  
       AND pokerhands.numberofplayers>=5 and  pokerhands.numberofplayers<=7
       AND (bigblind = 2 OR bigblind = 4 )
       AND player_id in 
        (SELECT player_id FROM playerhandscashkeycolumns GROUP BY player_id
         HAVING AVG(case didvpip when true then 100::real else 0 end) <= 20
         AND  HAVING AVG(case didvpip when true then 100::real else 0 end) > 10 )

如何“保存”拥有之后的值,以便我也可以从底部进行比较?谢谢你们。

4

2 回答 2

1

BETWEEN 对你有用吗?

HAVING AVG(case didvpip when true then 100::real else 0 end) BETWEEN 10 AND 20

(顺便说一句:丑陋的 SQL 语法,重用 AND 关键字)

更新:也可用于简化查询的其余部分:

AND pokerhands.numberofplayers BETWEEN 5 AND 7
AND bigblind IN ( 2, 4 )
于 2011-10-26T10:34:12.233 回答
1

这主要是@wildplasser已经指出的
.. 减去BETWEEN
.. plusJOIN而不是IN构造的错误,这在 PostgreSQL 中通常更快。
.. 更容易阅读

SELECT handhistories
FROM   handhistories
JOIN   pokerhands USING (pokerhand_id)  
JOIN   gametypes USING (gametype_id)
RIGHT  JOIN playerhandscashkeycolumns USING (pokerhand_id)
JOIN   (
    SELECT player_id
    FROM   playerhandscashkeycolumns
    GROUP  BY player_id
    HAVING avg(CASE WHEN didvpip THEN 100::real ELSE 0 END) >  10
    AND    avg(CASE WHEN didvpip THEN 100::real ELSE 0 END) <= 20
    ) p USING (player_id)
WHERE  pokerhands.site_id = 0  
AND    pokerhands.numberofplayers BETWEEN 5 AND 7
AND    bigblind IN (2,4);

您对某些列进行表限定,例如pokerhands.site_id,但不是其他列,例如 handhistories,您可能想要清理它。

于 2011-10-26T11:36:18.980 回答