0

According to this SO Question: MYSQL UPDATE: Is it possible to confirm some fields first?

We could do something like this with UPDATE in MySql:

UPDATE snakes_tb 
       SET snake_pic_urls= CONCAT(snake_pic_urls,'*".$newSnakePic."'), 
           snake_default_pic = IF(snake_default_pic = '' OR snake_default_pic = 'NO_PIC' ,'default_pic',snake_default_pic) 
WHERE snake_id={$id}

Notice the implementation of the IF statement. This method faces off the use of a Sub-query in the query.

However, having that in mind, how could we do something similar using the SELECT?

Assuming the following Example:

<?php
///The Bad String in with which columns should NOT be selected.
$badString ="_none";

In this Query, we have about 10 Columns that might contain the $badString; The Longest way and really impractical in some cases will be:

$selectQuery ="SELECT * FROM snakes_tb WHERE snake_is_deadly= 'Yes' AND col1 <> $badString AND col2 <> $badString AND col3 <> $badString AND col4 <> $badString AND col5 <>$badString etc...";

This way seems to be more accurate but kinda impractical should there be more than a reasonable number of columns to check against. Considering the UPDATEquery above with the IF statement, what could be the best way to successfully have a SELECT query that; 1) Will SELECT ALL Rows and Columns, 2) Display only data in rows that do not have columns with the $badString, without having to go the long way?

In other words, SELECT only rows where no column has a value of $badString

4

1 回答 1

2

This is the simplest I can think of:

SELECT *
FROM snakes_tb
WHERE '$badString' NOT IN (col1, col2, col3, col4, col5, ...)
AND snake_is_deadly = 'Yes'

There's no way to test a column without explicitly naming it in the query. If you don't want to hard-code all the column names in your code, you could use information_schema to get the list of columns and generate the query from that.

于 2013-07-05T17:06:38.947 回答