Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL returns incorrect data with use of join
    primarykey
    data
    text
    <p>I have join with a multiple tables. You can find the tables and MySQL query in this <a href="http://sqlfiddle.com/#!2/324ed/1" rel="nofollow" title="Sqlfiddle link for demo">demo</a>. </p> <p>These are the tables:</p> <ol> <li><p><strong>users</strong></p> <pre class="lang-none prettyprint-override"><code>id name 1 abc 2 xyz 3 pqr </code></pre></li> <li><p><strong>friend</strong></p> <pre class="lang-none prettyprint-override"><code>user_id friend_id 1 2 1 3 2 3 </code></pre></li> <li><p><strong>collection</strong></p> <pre class="lang-none prettyprint-override"><code>id user_id friend_id amount 1 1 2 100 2 2 1 -100 3 2 3 200 4 3 2 -200 5 1 3 300 6 3 1 -300 </code></pre></li> <li><p><strong>bill</strong></p> <pre class="lang-none prettyprint-override"><code>id use_id(bill_creator) 1 1 2 2 3 2 </code></pre></li> <li><p><strong>bill_person</strong></p> <pre class="lang-none prettyprint-override"><code>id bill_id user_id 1 1 1 2 1 2 3 1 3 4 2 2 5 2 3 6 3 2 6 3 1 </code></pre></li> </ol> <p>So far I have made this query:</p> <pre class="lang-sql prettyprint-override"><code>SELECT mf.id , mf.name , c.amount AS amount,count(bp.user_id) AS no_common_bills FROM ( SELECT fr.user_id AS user_id , fr.friend_id AS friend_id FROM friend fr JOIN users fru ON fru.id = fr.user_id WHERE fru.id IN (1) UNION SELECT fl.friend_id AS user_id , fl.user_id AS friend_id FROM friend fl JOIN users flf ON flf.id = fl.friend_id WHERE flf.id IN (1) ) f JOIN users mf ON mf.id = f.friend_id LEFT JOIN collection c ON c.friend_id = mf.id AND c.user_id = f.user_id LEFT JOIN bill_person bp ON bp.user_id=f.user_id AND c.friend_id = mf.id GROUP BY mf.id ORDER BY mf.id </code></pre> <p>and my <strong>output</strong> of this query is</p> <pre class="lang-none prettyprint-override"><code>id NAME AMOUNT NO_COMMON_BILLS 2 XYZ 100 2 3 PQR 300 2 </code></pre> <p>but I want this result:</p> <pre class="lang-none prettyprint-override"><code>id NAME AMOUNT NO_COMMON_BILLS 2 XYZ 100 2 3 PQR 300 1 </code></pre> <p>I am getting wrong output at <strong>NO_COMMON_BILLS</strong>. Other than that, all values are correct.</p>
    singulars
    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