Reputation: 273
I need a SQL Query that shows me all polls a user (uid) has not voted yet.
Example:
So I need the query that shows me the pid 2 he didnt vote yet.
This are the 2 tables:
CREATE TABLE IF NOT EXISTS `poll` (
`pid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`description` text NOT NULL,
`deadline` datetime NOT NULL,
PRIMARY KEY (`pid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
CREATE TABLE IF NOT EXISTS `votes` (
`vid` int(11) NOT NULL AUTO_INCREMENT,
`pid` int(11) NOT NULL,
`uid` varchar(20) NOT NULL,
`tid` int(11) NOT NULL,
`votes` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`vid`),
KEY `pcid` (`pid`,`uid`),
KEY `uid` (`uid`),
KEY `tid` (`tid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=19 ;
//edit this should make it more clear
Constraints for table votes
ALTER TABLE `votes`
ADD CONSTRAINT `votes_ibfk_3` FOREIGN KEY (`pid`) REFERENCES `poll` (`pid`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `votes_ibfk_4` FOREIGN KEY (`uid`) REFERENCES `user` (`uid`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `votes_ibfk_5` FOREIGN KEY (`tid`) REFERENCES `teams` (`tid`) ON DELETE CASCADE ON UPDATE CASCADE;
Can smbdy please help me. I guess it is a join with a WHERE and NOT LIKE but I just dont get it.
Merci!
Upvotes: 1
Views: 144
Reputation: 2284
SELECT
[poll].*
FROM
[poll]
LEFT OUTER JOIN [votes]
ON [votes].[pid] = [poll].[pid]
AND [votes].[uid] = @uid
WHERE
[votes].[vid] IS NULL
Upvotes: 1
Reputation: 1469
okay so this is my first answer. There might me more possibilities, but this should work.
SELECT * FROM Poll WHERE pid NOT IN (SELECT pid FROM votes WHERE uid = 1);
I'm not 100% sure this will work as I don't know the database type from which you're trying to retrieve your data.
Upvotes: 3
Reputation: 10976
Select
p.*
From
poll p
Where
Not Exists (
Select
'x'
From
Votes v
Where
v.pid = p.pid and
v.uid = <myuidvalue>
)
Upvotes: 0