2017-08-07 56 views
1

我的任务是获取包含关联品牌的所有产品的列表。Mysql - 从连接表和两个查询中将值导入列

我已经准备好以下表格:

posts | term_relationships  | term_taxonomy | terms 
---------|------------------------|------------------|--------- 
ID  | object_id    | term_taxonomy_id | term_id 
post_type| term_taxonomy_id  | term_id   | name 
brand_id |      | taxonomies     

它们以下列方式有关:

posts.ID -> term_relationships.object_id 
term_relationships.term_taxonomy_id -> term_taxonomy.term_taxonomy_id 
term_taxonomy.term_id -> terms.term_id 

领域之间的关联是由分配ID为每个连接映像的脚本制作:

Query result

在这一点上,如果关联存在,我必须开发查询来分配posts.brand_id值terms.term_id。

筛选标准是:

term_taxonomy.taxonomies="product_brand" 
posts.post_type= "products" 

查询逻辑可能是:

IF 
    term_taxonomy.taxonomies="product_brand" AND 
    term_taxonomy.term_taxonomy_id = term_relationships.term_taxonomy_id AND 
    term_relationships.object_id = posts.ID 
    THEN 
    INSERT INTO terms_term_id = brand_id 
ELSE 
    brands.brand_id IS NULL 

我试图把它翻译成MySQL,但没有成功。你有这个建议吗?

回答

1

您可以创建一个视图,然后从该视图创建SELECT,就像您可以对任何其他表格执行操作一样(当然,即使它看起来不是这样)。然后它就是你连接表格的物化视图。

如果您想查看优化程序的功能,请在其前面添加EXPLAIN。然后你会看到它的表现有多好。好吧,有点OT,但一般仍然是可取的。

也许对于IF你需要一个函数?我不确定。尽管如此,我仍会推荐对复杂查询的看法,因为它们可以隐藏更复杂查询背后的复杂查询。您仍可以再次执行WHEREORDER BY乃至JOIN。但要注意性能(当涉及到高负荷网站时,每JOIN和缺少索引伤害)。

好的,OT。也许这至少会给你一些提示。

+0

所以我要尝试一下意见。罗兰对不起,OT代表什么? – Alex

+0

OT = Off-Topic ...在上面的查询中,您有两个同名的列。您可能必须至少使用其中一个别名:'mg_term_relationships.term_taxonomy_id AS term_relation_taxonomy_id'或者可以重命名该列(如果需要)。 – Roland

+1

是的。我修好了,现在可以使用了。谢谢罗兰! – Alex

0

我试图创建视图:

create view brand2product as 
    select 
     mg_term_relationships.object_id, 
     mg_term_relationships.term_taxonomy_id , 
     mg_term_taxonomy.term_id , 
     mg_term_taxonomy.term_taxonomy_id , 
     mg_termS.term_id , 
     mg_terms.name 

    from mg_term_relationships 

    join mg_term_taxonomy on mg_term_taxonomy.term_taxonomy_id = mg_term_relationships.term_taxonomy_id 
    join mg_terms on mg_terms.term_id= mg_term_taxonomy.term_id 

    where mg_term_taxonomy.taxonomy="product_brand" 

它报告了以下错误:

#1060 Duplicate column name "term_taxonomy_id" 

本身工作正常查询。