有2个具有相同字段的表
表格
字段列表
product_setting_id
products_id
setting_constant_name
setting_value
如何从“store_product_settings”获取记录,如果在“store_product_settings”中找不到,则从“product_settings”表中获取
注意:没有联合查询
答案 0 :(得分:0)
您希望在表上使用左外连接,然后如果store_product_settings.setting_constant_name中的值为null,请使用product_settings中的值。
对于我的例子,我假设如下: 1)product_setting_id是每个表的顺序ID,并且是不相关的 2)products_id和setting_constant_name是搜索中使用的两个关键字段(如“我想为产品Y设置X”) 3)setting_value是您希望商店覆盖全局产品的值
所以我在表格中设置了以下值:
insert into product_settings (product_setting_id, products_id, setting_constant_name, setting_value) values (1,1,'S1','V1');
insert into product_settings (product_setting_id, products_id, setting_constant_name, setting_value) values (2,1,'S2','V2');
insert into product_settings (product_setting_id, products_id, setting_constant_name, setting_value) values (3,2,'S1','V1');
insert into product_settings (product_setting_id, products_id, setting_constant_name, setting_value) values (4,2,'S2','V2');
insert into product_settings (product_setting_id, products_id, setting_constant_name, setting_value) values (5,2,'S3','V3');
insert into store_product_settings (product_setting_id, products_id, setting_constant_name, setting_value) values (1,1,'S2','V2A');
insert into store_product_settings (product_setting_id, products_id, setting_constant_name, setting_value) values (2,2,'S1','V1A');
insert into store_product_settings (product_setting_id, products_id, setting_constant_name, setting_value) values (3,2,'S3','V3A');
首先,一个简单的左外连接来显示如何返回所有内容:
select ps.*, sps.*
from product_settings ps
left outer join store_product_settings sps
on ps.products_id = sps.products_id
and ps.setting_constant_name = sps.setting_constant_name
product_setting_id products_id setting_constant_name setting_value product_setting_id1 products_id1 setting_constant_name1 setting_value1
1 1 S1 V1
2 1 S2 V2 1 1 S2 V2
3 2 S1 V1 2 2 S1 V1
4 2 S2 V2
5 2 S3 V3 3 2 S3 V3
现在,只选择我们想要使用ifnull在store-value上的列来返回一般值:
select ifnull(sps.setting_value,ps.setting_value) as setting_value
from product_settings ps
left outer join store_product_settings sps on ps.products_id = sps.products_id
and ps.setting_constant_name = sps.setting_constant_name
给你这个:
setting_value
V1
V2A
V1A
V2
V3A
展开要捕获的其他字段的返回集。