MYSQL SQL语句。这条件查询可能吗?

时间:2012-04-06 03:48:00

标签: mysql sql conditional

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

我希望我想做的事情有道理。 总之,我需要根据原始选择中的字段值来连接不同的表。

3 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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'

答案 2 :(得分: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