【问题标题】:based on some condition we have to change the joining table根据某些条件,我们必须更改连接表
【发布时间】:2016-11-10 14:08:14
【问题描述】:

我面临一个问题。我正在创建一个类似 Temp_district 的过程。

其中有一个要求,例如基于某些条件,我们必须更改连接表。

like if(year=2016) then 
select * from table1 a join table2 b  on (a.id=b.id) join table3 c on (c.id=b.id) join table4 d on d.id=a.id


if(year<>2016) then
select * from table1 a join table2 b  on (a.id=b.id) join table3 c on (c.id=b.id) join table5 e on d.id=a.id;

查询几乎相同,查询量太大,如果这里的年份不是 2016 年,即 table4 到 table5,则只有一个表发生变化

有没有像下面这样的东西

if(year=2016) then 
with temp_table_2016 (select * from table4)
else with temp_table_2016 (select * from table6)

这样在单个查询中我可以用 temp_table_2016 替换 table4 或 table5,根据条件它会从所需表中获取数据。

【问题讨论】:

  • 解决方案取决于您使用的数据库。
  • 您在四个不同的数据库系统中面临这个问题?
  • 我在 DB2 中遇到了问题

标签: db2


【解决方案1】:

所以只需以相反的条件加入两者:

SELECT t.*,
        COALESCE(t4.col,t5.col) as col,
        COALESCE(t4.col2,t5.col2) as col2,
       ....
FROM t
LEFT JOIN t4 ON(t.id = t4.id AND year = 2016)
LEFT JOIN t5 ON(t.id = t5.id AND year <> 2016)

您需要在所有表格列上添加COALESCE(),这样只会显示相应的数据。如果您不在乎,可以同时选择它们,其中 1 个将始终为 NULL

【讨论】:

  • 非常感谢...解决方案运行良好...再次感谢您
  • 还有一个疑问,如果那个变化的表是第一个表,那么它的解决方案是什么......请帮助。
  • @RameshYelda 然后使用虚拟表.. SELECT * FROM (SELECT 1 as Dummy_Col) Dummy_Table LEFT JOIN Varying_Table_1 ON(Year = 2016) ... LEFT JOIN Varying_Table_2 ON (YEAR&lt;&gt;2016)...
【解决方案2】:

如果你使用 MSSQL,你可以这样实现它:

DECLARE @secondtable NVARCHAR(20)

if(year=2016)
BEGIN
SET @secondtable = 'table4'
END

if(year<>2016)
BEGIN
SET @secondtable = 'table5'
END



EXEC('select * from table1 a join table2 b
 on (a.id=b.id) join table3 c on (c.id=b.id) join '+@secondtable+' d on d.id=a.id')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2019-10-24
    • 2021-11-28
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多