单个SQL选择查询与单个大型SQLselect查询:什么是更好的&为什么?

时间:2012-06-21 12:52:37

标签: mysql sql query-optimization whmcs

我有三个单独的查询,这里是伪版本:

SELECT packageid from tblhosting where userid=1234 AND id=4351
SELECT id FROM tblcustomfields WHERE relid =tblhosting.packageid AND fieldname ='foo'
SELECT value FROM  `tblcustomfieldsvalues` WHERE  `fieldid` =tblcustomfields.id AND relid=tblhosting.id

目前,这些是单独的查询&它们显示为每个子查询。将它们组合成单个查询是否有意义?如果是,那么为什么&应该如何结合这个?

2 个答案:

答案 0 :(得分:1)

很抱歉有点密集,但您的问题似乎没有使用子查询。

如果真实代码使用子查询,则按

SELECT value 
FROM  `tblcustomfieldsvalues` 
WHERE  `fieldid` = 
   (SELECT id 
   FROM tblcustomfields 
   WHERE relid =(
     SELECT packageid 
     from tblhosting 
     where userid=1234 
     AND id=4351)
 AND fieldname ='foo')
AND relid=tblhosting.id

然后你只需要将它与@ Chopin的版本进行比较,就可以看出,从可读性的角度来看,连接更好。

联接也是执行此操作的惯用方法 - 大多数查看基于子查询的方法的SQL开发人员都会不顾一切;这使得它的可维护性和可扩展性降低。

就性能而言,我猜测查询优化器会认识到它们是等价的; “更好”的版本可能没有任何改进。

答案 1 :(得分:0)

查询可能是这样的:

SELECT value FROM tblcustomfieldsvalues
INNER JOIN tblcustomfields ON tblcustomfields.id = tblcustomfieldsvalues.fieldid
INNER JOIN tblhosting ON tblhosting.packageid = tblcustomfields.relid
WHERE tblcustomfields.fieldname = 'foo' AND tblhosting.userid = 1234 AND tblhosting.id = 4351

此处您将tblcustomfieldsvalues加入tblcustomfields,最后加入tblhosting。查看ON条件以确保它们已正确连接。

最后,对要约束的属性应用WHERE子句。

希望这有帮助!

相关问题