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
我的查询显示了这些结果(错误,未显示campaign_id.3):
campaigns_id campaigns_name cap count
1 Campaign1 2 2
2 Campaign2 1 1
如果我想要包含未被“WHERE”语句选择的值,我认为我接近错误,因为“服务”中没有与campaign.id ='3'的WHERE语句匹配的记录
答案 0 :(得分:2)
新编辑:
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
旧帖子:
我提出了这个查询,它产生了你想要的结果:
(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"
)
)
答案 1 :(得分:0)
将您的where子句更改为
WHERE served.ip = '127.0.0.1' OR served.ip IS NULL
答案 2 :(得分:-2)
LEFT JOIN表示从左表中提取所有记录,从右侧表中提取匹配记录。因此,来自id = 3的served.ip将为NULL。 因此,改变where条件使其成为
WHERE serverd.ip = '127.0.0.1' or serverd.ip IS NULL