我正在尝试获取所有我的帖子,其中投票IPAddress与我自己的匹配。这是我的SQL。 问题是,当我和其他人投票赞成时,我得到了投票。我认为这段代码说左边连接是可能的选择帖子,而且没有IPAddr = =我的。但这似乎并没有发生。我怎么写这个?
select * from Post
left join Vote as V on V.post=Post.id AND V.IPAddr<>123
where flag='1';
这是一些虚拟数据来说明问题。
create table P(id int primary key, body text);
create table V(id int primary key, val int, ip int, post int);
insert into P values(1,"aaa");
select * from P left join V on V.post=P.id where (V.ip is null or V.ip<>123);
insert into V values(1, 2,123,1);
select * from P left join V on V.post=P.id where (V.ip is null or V.ip<>123);
insert into V values(2, 2,13,1);
select * from P left join V on V.post=P.id where (V.ip is null or V.ip<>123);
答案 0 :(得分:4)
select *
from Post p
left join Vote as V on V.post=p.id
where (V.IPAddr is null or V.IPAddr<>123)
and flag='1';
<强>更新强>
select *
from P
left outer join V on V.post=P.id
where not exists (
select 1 from v
where IP = 123
and post = p.id
)
答案 1 :(得分:3)
这是你需要的吗?
SELECT * FROM P
WHERE NOT EXISTS
(SELECT * FROM V
WHERE V.post=P.id AND V.ip=123)
答案 2 :(得分:0)
也许就像......
SELECT *
FROM P
WHERE EXISTS (SELECT *
FROM V
WHERE V.IP IS NOT NULL AND
V.IP <> 123 AND
P.ID = V.POST);
正是您要找的。 p>