Table1
id | username | request
--------|--------------|----------
1 | user 1 | blah blah
2 | user 1 | blah2
3 | user 1 | blah3
4 | user 1 | blah4
5 | user 2 | blah1
Table2
id | username | requestID
--------|--------------|------------
1 | user 2 | 1
The returned results for 'user 2' should be:
table1.id = 2
table1.id = 3
table1.id = 4
I need to create a select that will select all id's from the first table where the username <> $username (thats easy enough).
I also need this matched against table 2 to ensure the $username does not already have said id from table 1 matching RequestID from table 2 (this is where I have no idea what to do).
I know how to do an inner join, but this seems a little more complex than that. Do I join two different selects together? How do I do this?
Existing code:
$stmt=$db->prepare("SELECT id FROM table1 WHERE username <> :user");
$stmt->bindParam(':user', $username);
$stmt->execute();
$row = $stmt->fetch();
Adding to question
I have tried a inner join and it just returns an error on the second WHERE clause: Unknown column 'table2.username' in 'where clause'.. yet looking the table clearly has a username column.
$stmt=$db->prepare("SELECT table1.id
FROM table1
INNER JOIN table2
ON table1.id = table2.requestID
WHERE table1.username <> 'user 1'
AND table2.username = 'user 1'");
ADDING MORE TO TRY TO MAKE IT MORE CLEAR
I do not believe a simple INNER JOIN will solve my problem as I originally stated. I need to first get the results from table1. Then I need those results tested against table2 so that ONLY results from table1 NOT MADE by the current user are returned, and of those returned results only the ones the user does not have listed in table2 should be returned.
So I am guessing I am just going to have to do two completely separate database functions.
$stmt=$db->prepare("SELECT id FROM table1 WHERE username <> :user");
$stmt->bindParam(':user', $username);
$stmt->execute();
$row = $stmt->fetch();
$id = $row['id'];
$stmt=$db->prepare("SELECT requestID FROM table1 WHERE username = :user");
$stmt->bindParam(':user', $username);
$stmt->bindParam(':id', $id);
$stmt->execute();
$rid = $stmt->fetch();
if $rid !== $id { //perform function } else {}
I thought there was a way to compound select statements so I didn't have to do 2 different calls, but perhaps I am wrong. Either way I don't see how inner join is going to accomplish this... but I am open to learning.
STILL MORE UPDATES TRYING TO MAKE THIS EVEN MORE CLEAR
table1.id = 1 should not match because user 2 has a table2.requestID that matches table1.id; table1.id = 5 should not match because user 2 is the listed username for table1.id = 5
However the other 3 columns should return.
ensure the $username does not already have said id from table 1 matching RequestID from table 2