Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select from a table where fields don't match conditions

Tags:

php

select

mysql

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?

like image 550
Belgin Fish Avatar asked Jul 20 '10 02:07

Belgin Fish


People also ask

Which type of join is used to find not matched data from table?

LEFT JOIN is used; this will return ALL rows from Table1 , regardless of whether or not there is a matching row in Table2 .

How do you join a table with no common fields?

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.

How do you get data from a table which is not present in another table?

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.


1 Answers

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)"; 
like image 160
Jeffrey Blake Avatar answered Oct 06 '22 23:10

Jeffrey Blake