views:

176

answers:

3

I apologize in advance for the non technincal description on this problem!

I have two tables: UsersOptions and OptionsList..

For simplicity sake, OptionsList is below:

  • ID - NAME
  • 1 - Red
  • 2 - Blue
  • 3 - Orange

UsersOptions has many rows eg;

  • ID - CLIENT - OPTION
  • 1 - John - Red
  • 2 - John - Orange
  • 3 - Mary - Red
  • 4 - Jill - Blue
  • 5 - Jill - Orange
  • etc..

Is there a query I can run that will give me the following output? (yes/no is not essential)

John's output:

  • OPTION - YES/NO
  • Red - y
  • Blue - n
  • Orange - y



Mary's output:

  • OPTION - YES/NO
  • Red - y
  • Blue - n
  • Orange - n

This is driving me crazy! Thanks to anyone that can help!

+1  A: 

You can use a CASE statement with an EXISTS sub-query:

SELECT
  NAME,
  CASE WHEN EXISTS 
       (SELECT ID FROM UsersOptions 
        WHERE CLIENT = 'John' AND `OPTION` = OptionsList.NAME)
       THEN 'y' ELSE 'n' END AS `YES/NO`
FROM
  OptionsList
Phil Ross
Ok this worked with a bit of tweaking (CLIENT needed to go in the top query):SELECT OptionsList.NAME, CASE WHEN EXISTS (SELECT ID FROM UserOptions WHERE UserOptions.OPTION = OptionsList.NAME AND UserOptions.CLIENT = 'John') THEN 'y' ELSE 'n' END AS `YES/NO`FROM OptionsListThanks so much! I had never even heard of CASE WHEN EXISTS before!
Sam
@Sam I've edited my response to move the CLIENT constraint (I clearly wasn't awake yesterday evening!).
Phil Ross
+1  A: 
SELECT
    o.NAME,
    CASE WHEN u.OPTION IS NULL THEN 'N' ELSE 'Y' END AS 'yes/no'
FROM
    OptionsList o
LEFT OUTER JOIN
    UsersOptions u
ON
    o.NAME = u.OPTION
WHERE
    u.CLIENT = 'John'
Paul Creasey
This imho will perform better than Phil's answer
LukeP
Ok I tried this just now, but it just returns the single line of the YES matches.. Should this be returning NO for rows that dont exist? Thanks!
Sam
As Sam says, this doesn't quite work. The WHERE constraint on UsersOptions effectively turns the LEFT OUTER JOIN into an INNER JOIN. This means options that the user does not have will not be returned. To fix this, remove the WHERE constraint and change the the join constraint to `ON o.NAME = u.OPTION AND u.CLIENT = 'John'`.
Phil Ross
A: 

This would work for John (adjust or remove WHERE clause as you see fit)

    SELECT t2.name AS name,
           IF(t1.option IS NULL, 'y', 'n') AS value
      FROM UserOptions AS t1
RIGHT JOIN OptionsList AS t2 ON (t1.option = t2.name)
     WHERE t1.client = 'John'

Though I do not understand why you did not normalize the option field in your UserOptions table. You went with the name value rather than id, for what reason?

Bor
This doesn't work. It will return two rows `('Red', 'n')` and `('Orange', 'n')`. To make it work, remove the WHERE constraint, change the join constraint to `ON t1.option = t2.name AND t1.client = 'John'` and swap the order of the `'y'` and `'n'` in the `IF` function.
Phil Ross