views:

78

answers:

3

I am trying to get all my post where Vote IPAddress doesnt match mine own. Here is my SQL. The problem is, i get the post i voted for when someone else also voted for it. I thought this code says select post when left join is possible and there are no IPAddr which == mine. But that doesnt seem to be happening. How do i write this?

select * from Post 
left join Vote as V on V.post=Post.id AND V.IPAddr<>123
where flag='1';

Here is some dummy data to illustrate the problem.

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);
+4  A: 
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'; 

Update:

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
)
RedFilter
Thats actually how i original wrote the code. It didnt work either thus the rewrite in the question above.
acidzombie24
Don't think I can do more without seeing data and example output.
RedFilter
Ok i'll see what i can do. I should have something within 10mins if i dont end up seeing the real mistake.
acidzombie24
Done. Check the edited question. you'll see how the SQL stops working (code included) when a 2nd V is inserted.
acidzombie24
It is not clear to me that anything is wrong. What is the expected output?
RedFilter
See my update - I think you are expecting no data to be returned as there only exists posts that you have voted for. Try the updated query and see if it works.
RedFilter
ahh a subquery. I was hoping i could do without. I think this may be my only subquery in the project.
acidzombie24
A: 

Perhaps something like...

SELECT *
    FROM P
    WHERE EXISTS (SELECT *
                      FROM V
                      WHERE V.IP IS NOT NULL AND
                            V.IP <> 123      AND
                            P.ID = V.POST);

is what you are looking for.

Brian Hooper
+3  A: 

Is this what you need?

SELECT * FROM P 
WHERE NOT EXISTS
     (SELECT * FROM V 
      WHERE V.post=P.id AND V.ip=123)
Martin Smith
ahh a subquery. I was hoping i could do without. I think this may be my only subquery in the project. Yes this is correct. Accepted the other because he helped before the edit.
acidzombie24