Welcome Guest, Not a member yet? Register   Sign In
Problem constructing a query [SOLVED]
#1

[eluser]Unknown[/eluser]
First off, I'm pretty new to SQL/MySQL so pardon me if this is retardedly obvious. I'm having a problem constructing a query for a MySQL database. I have a site that revolves around users voting on photos. Right now, it selects a random photo from the database for users to vote on. However, I want to change it so that it only selects photos that users haven't actually voted on. Obviously, saving the votes is trivial, but I'm having problems selecting new photos that a user hasn't voted on.

tl;dr version: Basically, what I want to do is select all the photos a given user has not voted for.

There are two tables, one with the photos, and another with all the votes. Here are abbreviated versions of the DESCRIBE output for each one.

Photos:
Code:
+----------+------------------+------+-----+---------+-------+
| Field    | Type             | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+-------+
| id       | varchar(32)      | NO   | PRI | NULL    |       |
+----------+------------------+------+-----+---------+-------+
Votes:
Code:
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id       | varchar(32) | NO   |     | NULL    |       |
| username | varchar(12) | NO   |     | NULL    |       |
| value    | varchar(5)  | NO   |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
Obviously the best way to do this would be with an EXCEPT statement, something like
Code:
(SELECT id FROM users) EXCEPT (SELECT id FROM votes WHERE username = 'username')
However, the EXCEPT statement has not yet been implemented in MYSQL(http://bugs.mysql.com/bug.php?id=1309). I tried to do it using a LEFT JOIN but I couldn't get it to work. Any suggestions?
#2

[eluser]JayTee[/eluser]
I made the assumption that the id field in your 'votes' table corresponds to a photo's id field:
Code:
SELECT photos.id
FROM photos
WHERE NOT EXISTS (
  SELECT *
  FROM votes
  WHERE
    votes.id = photos.id
    AND username = 'username'
)
#3

[eluser]Unknown[/eluser]
[quote author="JayTee" date="1235912280"]I made the assumption that the id field in your 'votes' table corresponds to a photo's id field:
Code:
SELECT photos.id
FROM photos
WHERE NOT EXISTS (
  SELECT *
  FROM votes
  WHERE
    votes.id = photos.id
    AND username = 'username'
)
[/quote]

Yes they do correspond. And thank you! That worked perfectly.




Theme © iAndrew 2016 - Forum software by © MyBB