(您可以理解更好的阅读here)
我想知道是否可以优化此查询:
SELECT id_type, value FROM Action, Action_set WHERE id_action = id_action_p1 AND id_action_set = 1
UNION ALL
SELECT id_type, value FROM Action, Action_set WHERE id_action = id_action_p2 AND id_action_set = 1
UNION ALL
SELECT id_type, value FROM Action, Action_set WHERE id_action = id_action_p3 AND id_action_set = 1
UNION ALL
SELECT id_type, value FROM Action, Action_set WHERE id_action = id_action_p4 AND id_action_set = 1
UNION ALL
SELECT id_type, value FROM Action, Action_set WHERE id_action = id_action_p5 AND id_action_set = 1
UNION ALL
SELECT id_type, value FROM Action, Action_set WHERE id_action = id_action_p6 AND id_action_set = 1
UNION ALL
SELECT id_type, value FROM Action, Action_set WHERE id_action = id_action_p7 AND id_action_set = 1
UNION ALL
SELECT id_type, value FROM Action, Action_set WHERE id_action = id_action_p8 AND id_action_set = 1
答案 0 :(得分:6)
尝试:
SELECT id_type, value
FROM Action, Action_set
WHERE id_action IN (id_action_p1,id_action_p2,id_action_p3,id_action_p4,id_action_p5,id_action_p6,id_action_p7,id_action_p8)
AND id_action_set = 1
如果有多行,请尝试:
SELECT id_type, value
FROM Action, Action_set
WHERE (id_action = id_action_p1
OR id_action = id_action_p2
OR id_action = id_action_p3
OR id_action = id_action_p4
OR id_action = id_action_p5
OR id_action = id_action_p6
OR id_action = id_action_p7
OR id_action = id_action_p8)
AND id_action_set = 1
答案 1 :(得分:0)
行;首先,您的查询没有达到预期的效果。假设您的一个动作有3个动作集; id_action_p1
,id_action_p2
和id_action_p3
。这意味着它会在Union All
查询中显示3个不同的项目,但具有相同的值 - 因为id_type和值都不取决于id_action。
如果是这样的话,你不能只使用或 - 它只会匹配一次 - 但你不止一次地回复物品而无法区分它们,这看起来很奇怪。如果是这样的话,我们可以通过在表格中包含项目列表并加入它来简化它。
首先,我们设置表格:
Select into Table_name id_action_p1 as action
Insert into Table_name (Select id_action_p2)
Insert into Table_name (Select id_action_p3)
Insert into Table_name (Select id_action_p4)
Insert into Table_name (Select id_action_p5)
...
接下来,我们编写新查询:
SELECT id_type, value
FROM Action, Action_set, Table_name
WHERE id_action=Table_name.action
AND id_action_set = 1
这应该与您之前的查询完全相同。