是否可以将这4个查询组合成一个更有效的查询?

时间:2015-08-21 22:33:38

标签: mysql

我希望我可以通过对数据库的单一查询来执行此操作:

// These four variables can change...
$weave = 10;
$grade = 4;
$model = 1;
$brim = 7;

现在我有这4个查询:

SELECT WeaveDesc FROM store_item_weaves WHERE ID = '$weave' LIMIT 1
SELECT GradeDesc FROM store_item_grades WHERE ID = '$grade' LIMIT 1
SELECT ModelDesc FROM store_item_models WHERE ID = '$model' LIMIT 1
SELECT BrimDesc FROM store_item_brims WHERE ID = '$brim' LIMIT 1

是否可以将所有这些加入到一个更有效的查询中?

3 个答案:

答案 0 :(得分:1)

您可以使用联合查询来实现此目的,如下所示:

(SELECT WeaveDesc FROM store_item_weaves WHERE ID = '$weave' LIMIT 1)
UNION
(SELECT GradeDesc FROM store_item_grades WHERE ID = '$grade' LIMIT 1)
UNION
(SELECT ModelDesc FROM store_item_models WHERE ID = '$model' LIMIT 1)
UNION
(SELECT BrimDesc FROM store_item_brims WHERE ID = '$brim' LIMIT 1)

数据库性能不会明显快于单独运行查询,并且实际上可能更难以操作结果集而不向结果集添加额外的列。

不言而喻,您应该遵循编程语言的最佳实践来使用参数化查询来防止SQL注入。

答案 1 :(得分:1)

试试这个:

SELECT
  (SELECT WeaveDesc FROM store_item_weaves WHERE ID = '$weave' LIMIT 1) AS WeaveDesc,
  (SELECT GradeDesc FROM store_item_grades WHERE ID = '$grade' LIMIT 1) AS GradeDesc,
  (SELECT ModelDesc FROM store_item_models WHERE ID = '$model' LIMIT 1) AS ModelDesc,
  (SELECT BrimDesc FROM store_item_brims WHERE ID = '$brim' LIMIT 1) AS BrimDesc

答案 2 :(得分:0)

如果所有查询都返回相同数量的字段,并且相应的字段具有相似的类型和含义,那么您可以使用UNION将这四个查询合并为一个查询:

(SELECT 'weave' AS item, WeaveDesc AS desc FROM store_item_weaves WHERE ID = '$weave' LIMIT 1)
UNION
(SELECT 'grade' AS item, GradeDesc FROM store_item_grades WHERE ID = '$grade' LIMIT 1)
UNION
(SELECT 'model' AS item, ModelDesc FROM store_item_models WHERE ID = '$model' LIMIT 1)
UNION
(SELECT 'brim' AS item, BrimDesc FROM store_item_brims WHERE ID = '$brim' LIMIT 1)

查询最多检索4行,每个表最多检索1行。每行都有item列(用它来知道每行提取的是什么表)和desc(从表中提取的实际值)。

四个单独的查询不一定运行得更快。它只节省了发送三个请求并再接收三个结果集所需的时间。