Search code examples
mysqlselectmultiple-value

MySQL SELECT rows which respond to specific MULTIPLE values in one of the columns


I've looked all over the Web, and in StackOverflow as well, and have found many similar topics, but none that answers specifically my needs. So I'm sending this out there, knowing there's probably some little thing I'm missing in order for it to work.

Let's imagine the following table:

      location  |   title   | description | quantity 
    ============|===========|=============|==========
      shelf     |   apple   |    red      |    2
      drawer    |   banana  |    yellow   |    4
      shelf     |   kiwi    |    green    |    2
      cupboard  |   lemon   |    yellow   |    1
      fridge    |   melon   |    orange   |    3
      drawer    |   peach   |    orange   |    1

What I want to do is select from this table all items that are either in the drawer or on the shelf (so drawer AND shelf) and then order them by, for example, first, location ascending and, second, quantity descending.

So what I have (after searching all over the web) is the following code, which is the only one that doesn't return an error, but it doesn't return any items either:

SELECT * FROM items WHERE location = 'shelf' AND location = 'drawer' ORDER BY location ASC, quantity DESC

Where am I going wrong? Any feedback will be greatly appreciated!

Usually questions go toward how to select values from multiple tables and then join them. However, I need values from only one table; however, these values need to respond to specific multiple values they share.


Solution

  • SELECT * FROM items WHERE location = 'shelf' or location = 'drawer'
    ORDER BY location ASC, quantity DESC
    

    or

    SELECT * FROM items WHERE location in ('shelf','drawer')
    ORDER BY location ASC, quantity DESC
    

    although for just two items, I'd probably go with the first myself, 3 or more, i might use in()

    Additional Info: The reason why you are getting no records returned is because you are using AND in your condition. Remember that there is one and only one value for every column in a row.