简体   繁体   English

用联接表求和

[英]sum and count with joined tables

Haven't come across a situation like this so not sure how to correct it. 没遇到过这样的情况,所以不确定如何纠正。 I'm guessing a sub query is needed? 我猜需要子查询吗?

I need the SUM of votes.vote and the COUNT of votes.vote . 我需要votes.votevotes.vote This allows me to calculate a rating (sum of all votes / # of votes = rating) for the location selected. 这使我可以为所选位置计算一个评分(所有投票的总和/投票数=评分)。

Here is the query with * and static binding to make it easier to understand : 这是带有*和静态绑定的查询,以使其更易于理解:

//prepare
$stmt = $db->prepare("
    SELECT SQL_CALC_FOUND_ROWS
        *,
        COALESCE(SUM(votes.vote),0) AS vote_total,
        COUNT(votes.vote) AS number_votes
    FROM locations
    LEFT JOIN tables
        ON tables.location_id = locations.location_id
    LEFT JOIN votes
        ON votes.location_id = locations.location_id
    LEFT JOIN events
        ON events.location_id = locations.location_id
    WHERE locations.location_id = :location_id
    LIMIT :limit OFFSET :offset
");

//bindings
$binding = array(
    'location_id' => 11,
    'limit' => 20,
    'offset' => 0
);

//execute
$stmt->execute($binding);

//results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

There are 11 events joined to this location. 此地点有11个活动。 There are only two votes joined to it (a value of 3 and a value of 4). 只有两票加入(值3和值4)。 I am getting the following : 我得到以下内容:

[vote_total] => 77 (should be 7, but is 7*11)
[number_votes] => 22 (should be 2, but is 2*11)

Aside from that only one result is returned rather than 11. If I remove the votes table join and the SUM/COUNT selects for it all 11 results are shown as they should be. 除此之外,仅返回一个结果,而不是11。如果我删除votes表,并且SUM / COUNT为此选择,则所有11个结果均应显示。

Is it possible to get the SUM and COUNT totals for votes.vote in the same query in some way or will a separate query be needed just to get those values? 是否可以通过某种方式在同一查询中获得vote.vote的SUM和COUNT总数,还是仅需要一个单独的查询即可获得这些值?

My best guess based on your description of the problem is that you want one row per event. 根据对问题的描述,我最好的猜测是每个事件需要一行。 If so: 如果是这样的话:

SELECT SQL_CALC_FOUND_ROWS e.*
       COALESCE(SUM(v.vote), 0) AS vote_total,
       COUNT(v.vote) AS number_votes
FROM locations l LEFT JOIN
     tables
     ON t.location_id = l.location_id LEFT JOIN
     votes v
     ON v.location_id = l.location_id LEFT JOIN
     events e
     ON e.location_id = l.location_id
WHERE l.location_id = :location_id
GROUP BY e.event_id
LIMIT :limit OFFSET :offset;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM