0

I'm ok with SQL but this one has me stumped. I'm about to give up on this but figured I'd post the question since other developers may find themselves looking for the same approach.

I'm working on an android multiselect AlertDialog. The dialog will be used to select values from key/code tables. In order to get this to work I need a query that returns a result set which has all of the key/code id's and values and another column with a boolean (or +1 and -1) indicating if the given person has that title. Here's the result set I need (using SQLite 3):

Given person.id = 1

TITLE.ID    TITLE.TITLE    PERSON_HAS_TITLE  
1           Parent         true OR +1
2           Teacher        true OR +1
3           Fireman        false OR -1
4           Policeman      false OR -1   


**PERSON**  
ID    NAME  
1     Sue  
2     Scott  
3     Jim  

**TITLE**   
ID    TITLE  
1     Parent  
2     Teacher  
3     Fireman  
4     Policeman

**PERSON_TITLE**  
PERSON_ID   TITLE_ID  
1           1  
1           2  
2           4 

Any ideas?

1 Answer 1

1

This will do it:

SELECT title.id,
       title.title,
       ( CASE
           WHEN EXISTS(SELECT person_id
                       FROM   person_title
                       WHERE  person_id = 1
                       AND    title_id = title.id) THEN 1
           ELSE -1
         END ) as person_has_title
FROM   title  

Alternatively, this will also work:

SELECT title.id,
       MAX(title.title) as title,
       MAX(CASE
             WHEN person_id IS NULL THEN -1
             ELSE 1
           END) as person_has_title
FROM   title
       LEFT JOIN person_title
         ON ( title.id = person_title.title_id and person_title.person_id = 1)
GROUP  BY title.id  
Sign up to request clarification or add additional context in comments.

2 Comments

wow, awesome....thanks...the second one works perfectly, the first one returns +1 for all rows...i never would have figured this out...thanks again.
There was an error on the first query, it should work as well now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.