Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL - Join a table twice with a main table
    primarykey
    data
    text
    <p>I'm not sure if this can be done. But I just wanted to check with the experts out here. </p> <p>My case is: I have a table tbl_campaign which basically stores a campaigns which has a one to many relation with a table called tbl_campaign_user where the users that were selected during the campaign are stored along with the campaign id (tbl_campagin_user.cu_campaign_id = tbl_campaign.campaign_id ).</p> <p>The second table (tbl_campaign_user) has a status field which is either 0 / 1 denoting unsent/sent. I wanted to write a single sql query which would read the campaign data as well as the number of sent and unsent campaign users (which is why I'm joining twice on the second table). I tried this below, but I get the same number of count as sent and unsent. </p> <pre><code>SELECT `tbl_campaign`.*, COUNT(sent.cu_id) as numsent, COUNT(unsent.cu_id) as num_unsent FROM (`tbl_campaign`) LEFT JOIN tbl_campaign_user as sent on (sent.cu_campaign_id = tbl_campaign.campaign_id and sent.cu_status='1') LEFT JOIN tbl_campaign_user as unsent on (unsent.cu_campaign_id = tbl_campaign.campaign_id and unsent.cu_status='0') WHERE `tbl_campaign`.`campaign_id` = '19' </code></pre> <hr> <p>I tried debugging by breaking the query into two parts: =></p> <pre><code>SELECT `tbl_campaign`.*, COUNT(unsent.cu_id) as num_unsent FROM (`tbl_campaign`) Left join tbl_campaign_user as unsent on (unsent.cu_campaign_id = tbl_campaign.campaign_id and unsent.cu_status='0') WHERE `tbl_campaign`.`campaign_id` = '19' </code></pre> <hr> <p>The above works exactly as wanted. And so does the one below:</p> <p>=></p> <pre><code>SELECT `tbl_campaign`.*, COUNT(sent.cu_id) as numsent FROM (`tbl_campaign`) Left join tbl_campaign_user as sent on (sent.cu_campaign_id = tbl_campaign.campaign_id and sent.cu_status='1') WHERE `tbl_campaign`.`campaign_id` = '19' </code></pre> <hr> <p>I am not sure what I've been doing wrong while merging the two. I know I don't know much about joins so possibly a conceptual error? Please could anyone help me?</p> <p>Thx in advance!</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