Mysql: Find a column name dependant on a value in the column, search for colunm name as value in another table

StackOverflow https://stackoverflow.com/questions/21870372

  •  13-10-2022
  •  | 
  •  

Question

G'day

I have 2 tables

RosterTable

ID: 1
Date: 19/02/14
UserA: N
UserB: N
UserC: Y
UserD: N

UserTable

ID: 1
Username: UserA
Name: John Smith
ID: 2
Username: UserB
Name: Joe Blogs
etc...

I'm trying to search the RosterTable to see who is rostered on indicated by the 'Y' and return the coulmn name, then use that column name to find the user details in the UserTable.

I can't change these tables as they a used for something else.

Thanks for any assistance

Was it helpful?

Solution

This is a very poor database design, if I understand the question correctly. Here is one way:

select *
from UserTable ut
where exists (select 1
              from RosterTable rt
              where rt.UserA = 'Y' and ut.username = 'UserA' or
                    rt.UserB = 'Y' and ut.username = 'UserB' or
                    rt.UserC = 'Y' and ut.username = 'UserC' or
                    rt.UserD = 'Y' and ut.username = 'UserD'
             );

OTHER TIPS

Here is a query. It should work. The main idea is to select the rows in RosterTable that has Y value for any of the 4 users and join UserTable with the associated id that is common in both table

 select * from RosterTable rt 
 where rt.UserA = 'Y' 
 or rt.UserB = 'Y' 
 or rt.UserC = 'Y' 
 or rt.UserD = 'Y' 
 inner join UserTable ut on ut.ID = rt.ID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top