Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Statement using Where clause with multiple values

Tags:

sql

I have a table that has multiple rows with the following fields:

PersonName SongName Status 

I want to use names selected from a multiple selection listbox, which I can retrieve the values, and then do a where clause so it shows the song names that the selected people can all play, therefore status is complete.

For example:

 PersonName      SongName    Status   Holly           Highland    Complete  Holly           Mech        Complete   Ryan            Highland    Complete 

If I select Holly and Ryan from the list box and press the button the query should just show Highland as that is what they both know.

like image 675
Sophie Avatar asked Apr 04 '12 14:04

Sophie


People also ask

Can WHERE clause have multiple values?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.

Can we use multiple conditions in WHERE clause in SQL?

You can use the OR condition in the WHERE clause to test multiple conditions where the record is returned if any one of the conditions are met. This example uses the WHERE clause to define multiple conditions, but instead of using the AND condition, it uses the OR condition.

How do I SELECT multiple values in SQL?

To select multiple values, you can use where clause with OR and IN operator.

How do I SELECT multiple values from the same column in SQL?

Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2);


2 Answers

Try this:

select songName from t where personName in ('Ryan', 'Holly') group by songName having count(distinct personName) = 2 

The number in the having should match the amount of people. If you also need the Status to be Complete use this where clause instead of the previous one:

where personName in ('Ryan', 'Holly') and status = 'Complete' 
like image 118
Mosty Mostacho Avatar answered Sep 19 '22 09:09

Mosty Mostacho


SELECT PersonName, songName, status FROM table WHERE name IN ('Holly', 'Ryan') 

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names
like image 27
sll Avatar answered Sep 21 '22 09:09

sll