繁体   English   中英

当字段是表名和主键时,mysql连接

[英]mysql join when field are table name and primary key

我必须在SugarCRM上构建一个复杂的查询才能生成报告。 SugarCRM关系存储在某些表上,因此我需要使用关系表连接多个表。 这些表具有一个modelmodel_id ,它们标识一个表并记录主ID。

下面是我尝试做的一个例子。

  • BLOGS:具有字段ID的主表

  • BLOG_ENTRY:具有字段ID,BLOG_ID(BLOGS表的FK)和POST_CONTENT_ID(下一个表BLOG_CONTENT的FK)的Blog子表

  • BLOG_CONTENT,具有字段ID,MODEL(标识子表)和MODEL_ID(标识子表ID)

  • 字段ID为BLOG_CONTENT_TABLE_ONE

假设我们可以有多个表BLOG_CONTENT_TABLE_TWO,...

查询应类似于:

select blogs.id, blog_content.model, blog_content.model_id, blog_content_table_one.id 
from blogs, blog_entry, blog_content, blog_content_table_one
where 

# join blog and blog_entry
blog.id = blog_entry.blog_id 

# join blog_entry and blog_content
AND blog_entry.content_id = blog_content.id 

# join blog_content and blog_content_table_one
AND blog_content.model = 'blog_content_table_one'
AND blog_content.model_id =  blog_content_table_one.id

这可行,但是如果有更多表,我想我应该使用MySQL的情况吗?

首先,对JOIN使用ON子句。 其次,我认为不可能获得所有可能的组合,但是对于三个博客内容表,您可以使用类似的方法。

SELECT 
    blogs.id, 
    blog_content.model, 
    blog_content.model_id, 
    blog_content_table_one.id 
    blog_content_table_two.id 
    blog_content_table_three.id 
FROM blogs
JOIN blog_entry 
    ON blog.id = blog_entry.blog_id
JOIN blog_content 
    ON blog_entry.content_id = blog_content.id
LEFT JOIN $blogtable1 blog_content_table_one 
    ON blog_content.model_id =  blog_content_table_one.id
    AND blog_content.model = '$blogtable1'
LEFT JOIN $blogtable2 blog_content_table_two 
    ON blog_content.model_id =  blog_content_table_two.id
    AND blog_content.model = '$blogtable2'
LEFT JOIN $blogtable3 blog_content_table_three 
    ON blog_content.model_id =  blog_content_table_three.id
    AND blog_content.model = '$blogtable3'
WHERE blog_content.model IN ('$blogtable1', '$blogtable2', '$blogtable3')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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