I’m trying to display all the users I have not voted on yet!
CREATE TABLE IF NOT EXISTS `users`
(`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(200) COLLATE utf8_unicode_ci NOT NULL,PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `whose_voted` (
`voter_user_id` int(11) NOT NULL,
`voted_on_user_id` int(11) NOT NULL,
PRIMARY KEY (`voter_user_id`,`voted_on_user_id`)
)
CREATE TABLE IF NOT EXISTS `votes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`yes_count` int(11) NOT NULL,
`beer_count` int(11) NOT NULL,
`total_votes` int(11) NOT NULL,
PRIMARY KEY (`id`)
)
CREATE TABLE IF NOT EXISTS `user_votes` (
`users_id` int(11) NOT NULL,
`votes_id` int(11) NOT NULL,
PRIMARY KEY (`users_id`)
)
I’ve got this query working:
/* Show the Names of all users that have not been Voted on */
SELECT users.name
FROM users
LEFT JOIN user_votes ON users.id = users_id
LEFT JOIN votes ON votes_id = votes.id
WHERE votes.id IS NULL
ORDER BY users.name
and this query works too
/* Show all the User Names that I have voted on */
SELECT users.id AS 'User ID', users.name AS 'I\'ve Voted On'
FROM users
INNER JOIN whose_voted ON users.id = voted_on_user_id
WHERE whose_voted.voter_user_id = 32 /* my User ID */
I’m stuck on showing the users that I haven’t voted on!
** Updated Working Query ****
/* Show a random users I have Not Voted For as of yet */
SELECT
unot.id, unot.name
FROM
users AS unot
WHERE NOT EXISTS (
/* Exclude the users you have voted on from the total user list */
SELECT uhave.id
FROM users AS uhave
INNER JOIN whose_voted ON uhave.id = voted_on_user_id
WHERE unot.id = uhave.id
AND (whose_voted.voter_user_id = 32)
)
AND (unot.id != 32)
AND (RAND()<(SELECT ((1/COUNT(*))*10) FROM users))
ORDER BY RAND()
LIMIT 1;
This bad boy spits out 1 random user at a time which I haven’t voted on! Thanks for your help, much aprpeciated!
As you could imagine, I’m voting on the random person that comes up, which puts them into the whose_voted table and thus nothing showing again the random query… Any SQL gurus who want to simplify my code? Cheers Mick
One method is to use a
WHERE NOT EXISTSwith your last query above as a subquery. Untested, of course, but should work.The
NOT EXISTSsubquery is likely to be slower than aJOINthough. Again, untested.