I'm just wondering what kind of SQL command I could execute that would select all items from a certain table where column A is not equal to x
and column B is not equal to x
Something like:
select something from table where columna does not equal x and columnb does not equal x
Any ideas?
LEFT JOIN is used; this will return ALL rows from Table1 , regardless of whether or not there is a matching row in Table2 .
Using the “FROM Table1, Table2” Syntax One way to join two tables without a common column is to use an obsolete syntax for joining tables. With this syntax, we simply list the tables that we want to join in the FROM clause then use a WHERE clause to add joining conditions if necessary.
We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.
The key is the sql query, which you will set up as a string:
$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";
Note that there are a lot of ways to specify NOT. Another one that works just as well is:
$sqlquery = "SELECT field1, field2 FROM table WHERE columnA != 'x' AND columbB != 'y'";
Here is a full example of how to use it:
$link = mysql_connect($dbHost,$dbUser,$dbPass) or die("Unable to connect to database"); mysql_select_db("$dbName") or die("Unable to select database $dbName"); $sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'"; $result=mysql_query($sqlquery); while ($row = mysql_fetch_assoc($result) { //do stuff }
You can do whatever you would like within the above while loop. Access each field of the table as an element of the $row array
which means that $row['field1']
will give you the value for field1
on the current row, and $row['field2']
will give you the value for field2
.
Note that if the column(s) could have NULL
values, those will not be found using either of the above syntaxes. You will need to add clauses to include NULL
values:
$sqlquery = "SELECT field1, field2 FROM table WHERE (NOT columnA = 'x' OR columnA IS NULL) AND (NOT columbB = 'y' OR columnB IS NULL)";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With