我问这个问题是为了寻求一些替代方法来获得我设法获得的相同结果,如下所述:
我有三个表:帐户(用户)、profile_parameters、Account_profile。默认情况下,帐户配置文件将获取基本系统配置 (profile_parameters) 中定义的参数值,但是,用户可以通过定义自己的首选项(获取存储的 Account_profile)来覆盖这些值,然后这些参数优先于基本系统配置。以下是表结构:
帐户:
Account_id
(PK)
更多专栏....
配置文件_参数:
prfl_param_id
(PK),
param_desc
, param_default_value
(这是系统基础配置值)
帐户资料:
account_id
(FK to Account),prfl_param_id
(FK to profile_parameter.param_value(用户定义的覆盖值)
我设法从下面的查询中得到了想要的结果,但我相信必须有另一种优雅的方式,因为我正在触发一个子查询来检查,另一个子查询来获取覆盖值,我没有这样做感觉舒服多了。
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
有什么建议????
最佳答案
您需要按如下方式使用左连接:
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
这里是 SQLFiddle ,
关于MySQL : Outer Join Query : Some alternate better approach (overriding field value by other table's field value only if available),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22870319/