MySql : Outer Join Query : Some alternate better approach (overriding field value by other table's field value only if available)

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

  •  27-06-2023
  •  | 
  •  

Domanda

I am asking this question to seek some alternate approach to get the same results which I managed to obtain as described below:

I have three tables: Account(a user), profile_parameters, Account_profile. By default, the account profile will get the parameter values defined in the base system config(profile_parameters) however, user can override those values by defining its own preference (which gets stored Account_profile), then those parameters take precedence over base system config. Following are the table structures:

Account: Account_id (PK) some more columns....

Profile_parameters: prfl_param_id (PK), param_desc, param_default_value (This is system base config value)

Account_profile: account_id(FK to Account), prfl_param_id(FK to profile_parameter. param_value(Overridden value defined by user)

I managed to get the desired result from following query but I believe there must be an alternate elegant way because I am firing one sub-query to check and the other sub-query to get the overridden value, about which I do not feel much comfortable.

SELECT a.account_id,pp.prfl_param_id, 
(CASE WHEN EXISTS (SELECT 1 FROM account_profile ap WHERE ap.account_id=a.account_id AND ap.prfl_param_id=pp.prfl_param_id ) 
      THEN (SELECT param_value FROM account_profile ap WHERE ap.account_id=a.account_id AND ap.prfl_param_id=pp.prfl_param_id ) 
ELSE  pp.default_value END) dfd 
FROM  account a, profile_parameters pp

enter image description here

Any suggestions ????

È stato utile?

Soluzione

You need to use left-join as follows:

select temp.account_id, temp.prfl_param_id,if(param_value is null,temp.param_default_value,param_value) dfd
from (
  select a.account_id, pp.prfl_param_id, param_default_value
  from account a, profile_parameters pp 
) temp left join account_profile ap on temp.account_id=ap.account_id and temp.prfl_param_id=ap.prfl_param_id

here is the SQLFiddle,

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top