单独的子选择以获得多个计数?

时间:2018-04-07 22:09:16

标签: sql postgresql count cross-join

我有这个问题:

SELECT  
(SELECT COUNT(media_id) FROM likes WHERE like_state = true AND media_id = ?) AS likes, 
(SELECT COUNT(media_id) FROM likes WHERE like_state = false AND media_id = ?) AS dislikes, 
(SELECT media_views FROM media_thumbnail WHERE media_id = ?) AS views;

它工作正常,但我不确定这是否是最佳方式。有什么建议吗?

我认为这不需要任何解释,但是......它会计算like_statetrue = like,false =有多少喜欢或不喜欢?不喜欢)并返回相关视频的观看次数。

2 个答案:

答案 0 :(得分:1)

使用表SELECT DISTINCT booking.booking_id, booking.price,shipment_log.pickup_city, shipment_log.pickup_state,shipment_log.delivery_city, shipment_log.delivery_state, tab.varPrice FROM booking INNER JOIN shipment_log ON booking.booking_id = shipment_log.booking_id AND booking.price = shipment_log.price INNER JOIN (select booking_id, VARIANCE(price) as varPrice from shipment_log group by booking_id ) tab ON tab.booking_id=booking.booking_id; 上的两个计数而不是两个单独的SELECT的单个likes肯定会更快:

SELECT

此查询与不相关的子查询之间存在角色 差异 ,原始查询包含两个隐式SELECT COUNT( like_state OR NULL) AS likes , COUNT(NOT like_state OR NULL) AS dislikes ,(SELECT media_views FROM media_thumbnail WHERE media_id = ?) AS views FROM likes WHERE media_id = ?; (逗号CROSS JOIN,列表中几乎与FROM相同)以及Gordon对最后一个子查询CROSS JOIN的回答。

前两个子查询总是返回一行,因此CROSS JOIN无法消除结果。 但是第三个查询可能找不到表CROSS JOIN中的给定media_id并返回 没有行 media_thumbnail导致整个查询CROSS JOIN

我在no row列表中使用子查询的查询将 no row 转换为空值,但仍返回结果行。使用SELECT

可以实现同样的目标

LEFT JOIN ... ON true中的子查询如果返回多行会引发异常 - 如果SELECT定义为media_thumbnail.media_idUNIQUE,则可能不会发生这种情况> 在任何情况下都不会发生。

关于条件计数:

漂亮而干净的语法将带有PRIMARY KEY子句:

FILTER

有点冗长,但可能更容易阅读。表现基本相同。

答案 1 :(得分:0)

您的查询没问题,但我更倾向于将其写为:

SELECT SUM( (l.like_state = true)::int ) as likes,
       SUM( (l.like_status = false)::int ) as dislikes,
       MAX(mt.media_views) as media_views
FROM likes l CROSS JOIN
     (SELECT media_views FROM media_thumbnail WHERE media_id = ?
     ) mt
WHERE l.media_id = ?;

这样可以节省一次扫描likes表的开销。