3

3我只是想知道这种类型的查询是否可能。如果是这样,我们将不胜感激。

    SELECT 

        field1,
        field2,
        field3

    FROM maintable

    WHERE maintable.field1 = passed_in_parameter


    IF (maintable.field2 = 1) THEN
            //do anything like joins
        INNER JOIN widgettable on widgettable.widgetid = field3

    ELSEIF (maintable.field2 = 2) THEN
            //do anything like joins
        INNER JOIN gizmottable on gizmottable.gizmoid = field3

    END IF

我希望我正在尝试做的事情是有意义的。总之,我需要根据原始选择中的字段值来连接不同的表。

4

3 回答 3

4

正如 zerkms 建议的那样,您可以将它们都从外部加入。请看以下是否有效

select mt.field1,
    mt.field2,
    mt.field3,
    CASE mt.field2 WHEN 1 THEN wt.widgetname WHEN 2 THEN gt.gizmoname END AS name 
from maintable mt
  left join widgettable wt
    on wt.widgetid = mt.field3
  left join gizmotable gt
    on gt.gizmoid = mt.field3
where mt.field1 = 'param'
   and ((mt.field2 = 1 and wt.widgetid is not null)
       or (mt.field2 = 2 and gt.gizmoid is not null))
于 2012-04-06T04:03:26.820 回答
1
SELECT 
    maintable.field1,
    maintable.field2,
    maintable.field3,
    CASE maintable.field2
    WHEN 1 THEN widgettable.widget_name
    WHEN 2 THEN gizmotable.gizmo_name
    END AS consolidated_name
FROM      maintable
LEFT JOIN widgettable ON widgettable.widgetid = maintable.field3
LEFT JOIN gizmottable ON gizmottable.gizmoid  = maintable.field3
WHERE     maintable.field1 = 'passed in parameter'
于 2012-04-06T04:02:05.003 回答
1

这听起来有点像 UNION 查询,只是您没有指定要查看连接表中的任何数据。这意味着内部连接是简单的存在性检查;他们检查连接表中是否有与主表中的行匹配的行。我已经采取了“激进”步骤,假设您需要连接表中的几列;您可以省略那些连接的列,而不会严重改变整体效果。此 UNION 查询假定您需要的 WidgetTable 和 GizmotTable 中的列非常相似。然后你可以写:

SELECT m.field1,
       m.field2,
       m.field3,
       w.column1,
       w.column3
  FROM maintable   AS m
  JOIN widgettable AS w ON w.widgetid = m.field3
 WHERE m.field1 = passed_in_parameter
   AND m.field2 = 1

UNION

SELECT m.field1,
       m.field2,
       m.field3,
       g.attribute23,
       g.attribute19
  FROM maintable   AS m
  JOIN gizmottable AS g ON g.gizmoid = m.field3
 WHERE m.field1 = passed_in_parameter
   AND m.field2 = 2

您正在寻找的直接类似物是:

SELECT m.field1, m.field2, m.field3,
  FROM maintable   AS m
  JOIN widgettable AS w ON w.widgetid = m.field3
 WHERE m.field1 = passed_in_parameter
   AND m.field2 = 1
UNION
SELECT m.field1, m.field2, m.field3,
  FROM maintable   AS m
  JOIN gizmottable AS g ON g.gizmoid = m.field3
 WHERE m.field1 = passed_in_parameter
   AND m.field2 = 2
于 2012-04-06T04:03:40.460 回答