2012-02-19 80 views
0

我困在一个MySQL查询中。我有一个临时医嘱表结构如下:有条件连接的Mysql查询

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

对于所有institutesstatesregionscountries我有单独的表。

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

如果我用left join 5个表格或使用union它可能是一个非常耗时的任务;所以我正在寻找不同的东西。

+0

你想如何这些连接取决于'product_type'字段?你能通过一个例子或样本数据来澄清吗? – 2012-02-19 12:24:20

+0

我想要的东西,如果product_type字段的值是研究所,然后执行与研究所表的联接,类似的,如果值是值是状态执行与状态表等连接。 – user1163513 2012-02-19 12:26:41

+0

如果你想所有的数据没有方式,但使用'联合'。 [Simon's answer](http://stackoverflow.com/a/9349119/458741)提到重组数据库,这似乎是目前最好的选择。 – Ben 2012-02-19 12:51:37

回答

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' 
)