MySQL 在这里加入最佳选择?
活动:
id name cap
1 Campaign1 2
2 Campaign2 1
3 Campaign3 1
服务:
id id_campaign ip
1 1 127.0.0.1
2 1 127.0.0.1
3 2 127.0.0.1
查询的结果应显示:
campaigns_id campaigns_name cap count
1 Campaign1 2 2
2 Campaign2 1 1
3 Campaign3 1 0
我正在使用此查询:
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
我的查询正在显示这些结果(不好,未显示campaigns_id.3):
campaigns_id campaigns_name cap count
1 Campaign1 2 2
2 Campaign2 1 1
我认为如果我想包含不包含的值,我正在接近错误t 被“WHERE”语句选择,因为“served”中没有与 Campaigns.id='3' 的 WHERE 语句匹配的记录
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 Campaign2 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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
新编辑:
旧帖子:
我想出了这个查询,它会产生您想要的结果:
NEW EDIT:
OLD POST:
I came up with this query, which produces the result you want:
将 where 子句更改为
Change your where clause to
LEFT JOIN 表示从左表中取出所有记录,并从右表中取出匹配的记录。因此,served.ip 将从 id=3 开始为 NULL。
所以改变where条件就可以了
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