Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get all names for a sql table?

I am having issue getting all of the names of people and whether they play rugby or not.

If they play then display Yes otherwise No. At the moment I am just getting a single result of a person who plays rugby not others who did not. Can anyone help me?

Current SQL:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

select P1.name, case when S.sport = 'rugby' then 'Yes' else 'No' end as rugby
    from Persons P1, 
         Persons  P2, 
         SportTogether S
    where P1.id = S.personA_id 
      and P2.id = S.personB_id
      and S.sport = 'rugby'
    group by case when S.sport = 'rugby' then 'Yes' else 'No' end;

>Solution :

In my opinion you are using a wrong approach. You want to select persons, so select from the persons table. You want to know whether a person plays rugby, so look up persons in the rugby table. Lookups can be done with IN or EXISTS.

select
  name,
  case when exists 
  (
    select null 
    from sporttogether s
    where s.sport = 'rugby'
    and p.id in (s.persona_id, s.personb_id)
  ) then 'Yes' else 'No' end as plays_rugby
from persons p
order by name;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading