我有三张桌子:
我想加入表格以获得结果中的列以满足:
如果tags.tag_name ="输入"和tags.value =" Silver"那么它应该包含两个条目 - taxons.name和concat(tags.value,taxon.name) 例如。
products_taxons#1,1
分类#1,"耳环" ...
标签#1,1,"类型","银"
结果列应包含"耳环"和" SilverEarrings"
如果tags.tag_name ="输入"和tags.value =" Precious"那么它应该包含一个条目 - concat(tags.value,taxon.name)
products_taxons#2,1
分类#1,"耳环" ...
标签#2,2,"输入"," Precious"
结果列应包含" PreciousEarrings"
我编写了以下sql查询。它有效,但是有更好的,最佳的方式吗?
select pt.product_id as product_id, concat(tag.value,t.name) as taxon
from taxons as t
inner join products_taxons as pt on t.id = pt.taxon_id
left join tags as tag
on tag.taggable_id = pt.product_id and (tag.value='Precious' or tag.value='Silver')
UNION ALL ( select pt.product_id as product_id, t.name as taxon
from taxons as t
inner join products_taxons as pt on t.id = pt.taxon_id
left join tags as tag
on tag.taggable_id = pt.product_id
where tag.value='Silver' )
编辑:示例,请考虑以下表格条目
product_id | taxon_id
------------+-----------
1000000001 | 1
1000000002 | 2
1000000003 | 3
id | name
-----------+---------------
1 | Necklace Sets
2 | Earrings
3 | Bracelets
product_id | tag_name | value
------------+-----------------------+--------------------------------------------
1000000001 | type | Silver
1000000002 | type | Precious
1000000003 | occasion | Everyday Wear
我想要以下结果
product_id | taxon
------------+-----------
1000000001 | Necklace Sets
1000000001 | SilverNecklace Sets
1000000002 | PreciousEarrings
1000000003 | Bracelets
答案 0 :(得分:0)
我认为这就是你要找的东西:
select pt.product_id as product_id,
case tag.value when "Silver" then concat(tag.value,t.name)
when "Precious" then concat(tag.value,t.name)
else t.name
end as taxon
from taxons as t
inner join products_taxons as pt on t.id = pt.taxon_id
left join tags as tag
on tag.product_id = pt.product_id