[英]How to select from two columns in different tables conditionally
I have two tables 我有两张桌子
1. products <id, taxon, .... >
2. tags <id, tag_name, product_id, value, ....>
I want to join (or do some other operation) on these two tables to get taxon but based on the value of a particular tag_name. 我想在这两个表上联接(或执行一些其他操作)以获得分类,但是基于特定tag_name的值。 Let me make it more clear, if a product has tag with tag_name=type
and value=precious
, I want to treat this tag value as a taxon. 让我更明确地说,如果产品的标签具有tag_name=type
和value=precious
,那么我想将此标签值视为一个分类单元。
So if I have following entries: 因此,如果我有以下条目:
<# product id:1, taxon:"Jewellery">
<# product id:2, taxon:"Apparel">
<tag id:1, tag_name:"type", product_id:1, value="Precious">
I want the following in the result table 我想要结果表中的以下内容
product_id taxon_name
1 Jewellery
1 Precious
2 Apparel
How can I form such a query? 如何形成这样的查询?
Thanks 谢谢
This is tricky... 这很棘手...
A UNION might do it. 一个UNION可能会这样做。 See what this results in: 看看结果如何:
SELECT id,taxon
FROM products
UNION ALL (
select product_id as id,value as taxon
from tags
where tag_name='type' and value='Precious'
);
Basically, that loads id
and taxon
from products, and then appends to the end (in a manner of speaking) two relevant columns from the tags
table. 基本上,这会从产品中加载id
和taxon
,然后(以某种方式)将tags
表中的两个相关列附加到末尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.