Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL: count votes for users
    text
    copied!<p>I'm searching for a way to count votes for a user in a MySQL database.</p> <p><strong>Tables and Columns:</strong></p> <pre><code>companion - companion_id - news_id - user_id news - news_id - user_id user - user_id - user_name vote - vote_id - news_id - user_id </code></pre> <p>check out the <strong><a href="http://sqlfiddle.com/#!2/841d9f/14" rel="nofollow">SQL Fiddle Live Demo</a></strong></p> <p><strong>Conditions:</strong></p> <ul> <li>every <em>user</em> can have several <em>news</em></li> <li>every <em>news</em> can have several <em>votes</em></li> <li>every <em>news</em> can have several <em>companions</em> (companions are user)</li> <li>every <em>user</em> can vote for several <em>news</em> (not important for this query)</li> </ul> <p><strong>Target:</strong></p> <p>Now I'm trying to figure out how many votes a user has together: on his own news an on which he is linked as a companion. The solution should be a <strong>single</strong> MySQL query.</p> <p><strong>Example for <em>User2</em>:</strong></p> <ul> <li><em>User2</em> has <strong>1</strong> news article. This news article has <strong>2</strong> votes.</li> <li><em>User2</em> is companion of <strong>1</strong> article. This news article has <strong>3</strong> votes.</li> <li><em>User2</em> should have <strong>5</strong> votes </li> </ul> <p><strong>Approach:</strong></p> <p>The following query results 31 and not 5, because it can't group it correct over 2 differnt tables.</p> <pre><code>SELECT u.user_name, u.user_id, COUNT(v.vote_id) AS votes FROM user u, news n, companion c, vote v WHERE u.user_id = 2 AND ( ( u.user_id = n.user_id AND n.news_id = v.news_id ) OR ( u.user_id = c.user_id AND c.news_id = v.news_id ) ) GROUP BY u.user_id LIMIT 1 </code></pre>
 

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