Thursday, April 21, 2011

MySQL Get All Except If

I have a MySQL table and I want to extract all rows except if the column contains a specific value. Is this possible?

My table structure

+----+------+------+------+
| ID | col1 | col2 | col3 |
+----+------+------+------+
|  1 | blah | blah | boo  |
+----+------+------+------+
|  2 | blah | blah | blah |
+----+------+------+------+
|  3 | blah | blah | boo  |
+----+------+------+------+

So if col3 contains boo, don't extract that:

+----+------+------+------+
| ID | col1 | col2 | col3 |
+----+------+------+------+
|  2 | blah | blah | blah |
+----+------+------+------+
From stackoverflow
  • The following excludes col3 if it equals 'boo'.

    select * from mytable where col3 <> 'boo'

    Other than that, I don't know what you're looking for.

    Ben Shelock : That's not what I mean. Due to the way my table is structured this would not be possible.
    Adam Bernier : @Ben: please post an example of your table structure to add some lubrication to the discussion.
    musicfreak : @Ben: Yes, please explain. I don't see why this wouldn't work.
  • It's certainly possible. The following code should do the trick

    SELECT * FROM `table` WHERE `column` != "boo"
    

    If you're looking where more than one column, than add the following afterwords:

    && `column` != "boo"
    

    for every column you need.

    Assuming, of course, that you mean that you DON'T want boo. If you want only boo, then take away the exclamation point.

    SleepyCod : I would recommend using the "AND" keyword instead of "&&"...
    Ben Shelock : This is my query however I get an error. Can you spot the problem? SELECT * FROM `links` WHERE `page` ='$id' AND WHERE `season` !='*' ORDER BY `season` ASC, `episode` ASC
    waiwai933 : Take out the second Where. That should be your problem.
  • If by "contains" you mean "is equal to":

    SELECT * FROM table WHERE column <> 'VALUE TO EXCLUDE'
    

    Or if by "contains" you literally mean "contains":

    SELECT * FROM table WHERE column NOT LIKE '%VALUE TO EXCLUDE%'
    

    EDIT -- To answer your updated question:

    SELECT * FROM table WHERE col3 <> 'boo'
    
  • select * from MyTable where col3 <> 'boo'

  • You can use regular expressions in your where clause if your cloumn data and requirement are not simple.

    e.g.

    SELECT * FROM foo WHERE bar REGEXP '[[:alnum:]]+';
    

    or

    SELECT * FROM foo WHERE bar NOT REGEXP '[[:alnum:]]+';
    
  • SELECT * FROM YourTable WHERE col3 != 'boo';
    

0 comments:

Post a Comment