all the candiates belongs to agency code 3 and not found in approval tables.
$$agency_code='3'
$query="SELECT candidates.* from candidates, approvals" .
" WHERE (candidates.cid <> approvals.cid) AND candidates.agency_code='$agency_code'";
SELECT
something
, anything
, just_not_the_dreaded_star
FROM
candidates
WHERE
agency_code = 3
AND
cid NOT IN
(
SELECT
id
FROM
approvals
)
Off Topic:
Also, you may want to have a look at parameter escaping to prevent SQL injection. Either use mysqli_real_escape_string if you’re using MySQLi, or use prepared statements if you’re using PDO.
But i am confused. why my query was working correctly when i test for = ?
ex:
$agency_code='3'
$query="SELECT candidates.* from candidates, approvals" .
" WHERE (candidates.cid [B][COLOR="#006400"]=[/COLOR][/B] approvals.cid) AND candidates.agency_code='$agency_code'";
This produce correct results if i want to display all approved candaites. but when i change the = to <> strage results ?
Also, you may want to have a look at parameter escaping to prevent SQL injection. Either use mysqli_real_escape_string if you’re using MySQLi, or use prepared statements if you’re using PDO.
The way you posed your query you will get a Cartesian_product. That is to say, you will get a combination of all rows from the candidates table with all rows in the approvals table, like this:
So when you query with = you will get all rows I’ve highlighted in red above, which is what you expected (even though it’s not the correct way to achieve it, the correct way would be to use an INNER JOIN). No when you change = to <> you will get all the rows for which the agency_code is 3 and the first column of the table above isn’t equal to the last column, which is pretty much most of the rows that have agency_code = 3.
To visualise, these are the rows you get back from that query:
SELECT something
, anything
, just_not_the_dreaded_select_star
FROM candidates
LEFT OUTER
JOIN approvals
ON approvals.cid = candidates.cid
WHERE candidates.agency_code = 3
AND approvals.cid IS NULL