I’m building a survey thing, and have three tables: users, questions, answers, where answers contains a record for each question a user has answered (and no record if they haven’t answered a given question yet).
My data structure is something like this:
CREATE TABLE users (
id INT NOT NULL,
name VARCHAR(255),
PRIMARY KEY (id)
)
CREATE TABLE questions (
id INT NOT NULL,
text VARCHAR(255),
PRIMARY KEY (id)
)
CREATE TABLE answers (
id INT NOT NULL,
id_q INT NOT NULL,
id_u INT NOT NULL,
answer VARCHAR(255),
PRIMARY KEY (id),
FOREIGN KEY (id_q) REFERENCES questions(id),
FOREIGN KEY (id_u) REFERENCES users(id)
)
I’ve tried a few rudimentary things with LEFT JOIN and such to no avail. I’ve used ORDER BY RAND() LIMIT 0,1 for the randomness part of the problem. I’m suspecting this isn’t as straightforward as I thought. (I’m teaching myself SQL .. would I need to use one of those subquery things I don’t know about yet?)
How do I write the MySQL to select a random question which doesn’t have a corresponding answer from a nominated user?
You were on the right track with
LEFT JOIN…You can use it to make an inverse selection of an
INNER JOINwithWHERE column IS NULL. It’s this simple: