开发者

MySQL Join the Best Option Here?

开发者 https://www.devze.com 2023-03-06 15:24 出处:网络
campaigns: idnamecap 1Campaign12 2Campaign21 3Campaign31 served: idid_campaignip 11127.0.0.1 21127.0.0.1 32127.0.0.1

campaigns:

id     name            cap
1      Campaign1       2
2      Campaign2       1
3      Campaign3       1

served:

id     id_campaign     ip
1      1               127.0.0.1
2      1               127.0.0.1
3      2               127.0.0.1

The result of the query should display:

campaigns_id    campaigns_name          cap    count
1               Campaign1               2      2
2               Camp开发者_高级运维aign2               1      1
3               Campaign3               1      0

I am using this query:

   SELECT served.id_campaign, 
          campaigns.name, 
          campaigns.cap, 
          COUNT( served.id ) AS count
     FROM campaigns
LEFT JOIN served ON campaigns.id = served.id_campaign
    WHERE served.ip =  '127.0.0.1' 
 GROUP BY served.id_campaign

My query is displaying these results (bad, not showing campaigns_id.3):

campaigns_id    campaigns_name          cap    count
1               Campaign1               2      2
2               Campaign2               1      1

I am thinking I am approaching wrong if I want to include values that aren't being selected by the "WHERE" statement as there are no records in "served" that match the WHERE statement for campaigns.id='3'


NEW EDIT:

   SELECT campaigns.id as id_campaign, 
          campaigns.name, 
          campaigns.cap, 
          COUNT( served.id ) AS count
     FROM campaigns
LEFT JOIN served ON campaigns.id = served.id_campaign
      AND served.ip =  '127.0.0.1' 
 GROUP BY campaigns.id

OLD POST:

I came up with this query, which produces the result you want:

(SELECT served.id_campaign, 
          campaigns.name, 
          campaigns.cap, 
          COUNT( served.id ) AS count
     FROM campaigns
LEFT JOIN served ON campaigns.id = served.id_campaign
    WHERE served.ip =  '127.0.0.1' 
 GROUP BY served.id_campaign)

UNION

(SELECT id, name, cap, 0 as count 
FROM campaigns 
WHERE id <> ALL 
     (
      SELECT campaigns.id 
      FROM campaigns, served 
      WHERE campaigns.id = served.id_campaign AND served.ip = "127.0.0.1"
     )
)


Change your where clause to

WHERE served.ip =  '127.0.0.1' OR served.ip IS NULL


LEFT JOIN says that bring all the records from left table and the matching records from the right hand side table. So the served.ip would be NULL from id=3. So change the where condition to make it

WHERE serverd.ip = '127.0.0.1' or serverd.ip IS NULL
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号