Note that there are some explanatory texts on larger screens.

plurals
  1. POLeft joins --> aggregate function problem
    primarykey
    data
    text
    <p>I have four different tables in my database:</p> <p><strong>thread:</strong> </p> <ul> <li>thread_id</li> <li>thread_content</li> <li>timestamp</li> </ul> <p><strong>thread_rating:</strong></p> <ul> <li>thread_rating_id</li> <li>thread_id</li> <li>liked</li> <li>disliked</li> </ul> <p><strong>thread_report:</strong></p> <ul> <li>thread_report_id</li> <li>thread_id</li> </ul> <p><strong>thread_impression:</strong></p> <ul> <li>thread_impression_id</li> <li>thread_id</li> </ul> <p>And I'm going to join on these tables with this SQL-Query</p> <pre><code>SELECT t.thread_id, t.thread_content, SUM(tra.liked) AS liked, SUM(tra.disliked) AS disliked, t.timestamp, ((100*(tra.liked + SUM(tra.liked))) / (tra.liked + SUM(tra.liked) + (tra.disliked + SUM(tra.disliked)))) AS liked_percent, ((100*(COUNT(DISTINCT tre.thread_report_id)) / ((COUNT(DISTINCT ti.thread_impression_id))))) AS reported_percent FROM thread AS t LEFT JOIN thread_rating AS tra ON t.thread_id = tra.thread_id LEFT JOIN thread_report AS tre ON tra.thread_id = tre.thread_id LEFT JOIN thread_impression AS ti ON tre.thread_id = ti.thread_id GROUP BY t.thread_id ORDER BY liked_percent </code></pre> <p>The Query should return all thread_ids with the calculated liked and disliked, the likes in percent, the timestamp, when the thread was inserted into the database and the reports in percent to the impressions (the times, the thread was shown to the user)...</p> <p>Nearly all results are right, the only results which are not right are the likes and dislikes.</p> <p>If I put a count(*) in front of the query, I can see, that the right results have a count of 1 and the wrong ones have sometimes a count of up to 60. Seems like there are cross join-problems...</p> <p>I think that this is an issue with the Grouping, or perhaps I should embrace the Joins.</p> <p>I've seen solutions with subselects. But I don't think that this is a great solutions for this issue...</p> <p>What am I doing wrong here?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload