简体   繁体   中英

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. 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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM