简体   繁体   中英

MySQL WHERE clause selects values then omits some based on another column?

I have a pretty simple question (I think) but I can't seem to find an answer anywhere. I'm sure I'm over-thinking this but I would like insight nonetheless.

Using MySQL, I would like to SELECT rows in a table based on a column using a WHERE clause and then refine that search based on another column. More specifically, I would like to return all entries from a specific user that haven't yet been archived.

Here is what I have today:

"SELECT * FROM entries WHERE user_id = '4' AND archived <> 'yes'";

This is not working so I tried:

"SELECT * FROM entries WHERE (user_id = '4' AND archived <> 'yes')";

But that hasn't worked either.

Do I need to return all the entries from that user and then remove from that array all of the entries that have an 'archive' value of 'yes' with a for loop or something using my scripting language?

Thank you in advance for the help!

one idea is to change the yes or no answer to a 0/1 true false statement. Make it so your archived are set to 0 and the default is 1 so then you could do

$query = <<<SQL
   SELECT id,title,name,etc 
   FROM entries 
   WHERE user_id = :id 
   AND archived = :true
SQL;
   $results = $this->dbconn->prepare( $query );
   $results->execute( array (
       ':id'  => $_GET['id'],
       ':true'=> 1,
    ));
   if($results->rowCount() < 1) 
   {
   echo "No Unarchived for this user";
   }
   else {
    //Pull Unarchived Data
   }

You didn't have any actual PHP so if you're unfamiliar with what I've posted it's PDO and I recommend reading into it.

If there are NULL values in the archived column, then those rows will not satisfy the inequality predicate. (It's the ages old issue of boolean three-valued logic... TRUE , FALSE and NULL .)

There's a couple of ways to deal with NULL values, to get those returned.

As one option, you could make use the (MySQL specific) NULL-safe comparison operator: <=> .

For example:

... WHERE user_id = '4' AND NOT (archived <=> 'yes')

That's effectively equivalent to the more ANSI-standard compliant:

... WHERE user_id = '4' AND (archived <> 'yes' OR archived IS NULL)

Reference: https://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#operator_equal-to

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM