Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Select Statement, WHERE 'IN' Clause

I currently have the following row in my table:

         course_data:
             user_id        days     <-- This is a varchar column.
               405          1,3,5

and I am trying to implement the following SELECT statement:

SELECT usrID, usrFirst, usrLast, usrEmail
    FROM tblUsers
    WHERE usrID NOT IN
    (
        SELECT users.usrID
            FROM
                `course_data` courses,
                `tblUsers` users
            WHERE
                days IN ('$day')
    )
    GROUP BY usrID
    ORDER BY usrID

Basically, I want that row (with user 405) to be omitted if the $day variable includes a '1, 3, or 5'.

For example, if $day = "1", it should return an empty query (because the number "1" is in the column "1,3,5").

However, I have not found this to be the case. Even though $day = "1", it still returns that row.

The only way that it won't return the row is if $day= "1,3,5." Yet, I thought that the IN() clause would take any part of my variable and apply it to that column.

Any insights on what I'm doing wrong here? Thanks.

like image 683
Dodinas Avatar asked Oct 18 '09 21:10

Dodinas


People also ask

Can we use SELECT statement in WHERE clause?

You should use the WHERE clause to filter the records and fetching only the necessary records. The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters.

WHERE clause is used in MySQL for?

The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition.

How do you use WHERE in SELECT?

WHERE clause Syntax. The basic syntax for the WHERE clause when used in a MySQL SELECT WHERE statement is as follows. “WHERE” is the keyword that restricts our select query result set and “condition” is the filter to be applied on the results. The filter could be a range, single value or sub query.

Can we use two WHERE clause in MySQL?

MySQL allows you to specify multiple WHERE clauses. These clauses may be used in two ways: as AND clauses or as OR clauses. What is Operator? An operator is a special keyword used to join or change clauses within a WHERE clause.


1 Answers

Remove the Quotes in the IN Statement. The Syntax is:

... WHERE column IN (1,2,3) 

and not as you used it

... WHERE column IN ('1,2,3')

Also see the documentation on IN, there are more examples.

like image 92
theomega Avatar answered Sep 19 '22 18:09

theomega