带条件连接的Mysql查询

时间:2012-02-19 12:17:55

标签: mysql join

我坚持使用MySQL查询。我有一个临时订单表,其结构如下:

session_id
product_id
product_type -- 'institute','state','region','country' 

对于所有institutesstatesregionscountries,我都有单独的表格。

我想创建一个MySQL查询,该查询从临时表中获取数据,并根据product_type字段与相应的表进行连接。

如果我将left join与5个表一起使用或使用union,那么这可能是一个非常耗时的任务;所以我一直在寻找不同的东西。

1 个答案:

答案 0 :(得分:2)

我建议您查看此问题中的答案,因为它们似乎符合您的具体问题https://stackoverflow.com/a/9327678/1213554

简短的版本是,为了能够有效地执行此请求,我担心可能需要进行数据库重组。

您正在寻找的具体内容是不可能的,您必须使用UNION来执行以下操作。正如你所说,这将是一项耗时的任务。

(
    SELECT tempData.*
    FROM tempData
    INNER JOIN institutes 
    ON institutes.id = tempData.product_id
    WHERE tempData.product_type = 'institute'
) UNION (
    SELECT tempData.*
    FROM tempData
    INNER JOIN states 
    ON states.id = tempData.product_id
    WHERE tempData.product_type = 'state'
) UNION (
    SELECT tempData.*
    FROM tempData
    INNER JOIN regions
    ON regions.id = tempData.product_id
    WHERE tempData.product_type = 'region'
) UNION (
    SELECT tempData.*
    FROM tempData
    INNER JOIN countries
    ON countries.id = tempData.product_id
    WHERE tempData.product_type = 'country'
)
相关问题