【发布时间】:2016-01-17 09:42:50
【问题描述】:
我有两个表 hsc,sslc hsc:
id name class section
1 karna 1 a
2 bavi 2 b
3 chidu 3 c
sslc
id name class section
1 ram 11 a2
2 sam 11 b1
3 guna 14 c2
注意:存在于 hcs 中的类不会存在于 sslc 中。 我应该只传递 id 和 class 作为使用 php 获取结果的条件,但我不会传递表名。所以我正在使用联合查询
$id=$_REQUEST['id'];
$class=$_REQUEST['class'];
$sql="select t1.* (select id,name,class,section from hsc union select id,name,class,section from sslc)t1 where id=$id and class=$class;"//this runs successfully
$StudentArray = $Cobj->union($sql);
或
$sql="select * from hsc where id=$id and class=$class;"
$StudentArray = $Cobj->union($sql);
if(count($StudentArray)>0){
$table="hsc";}
else{
$table="sslc";}
$sql="select * from $table where id=$id and class=$class";
$StudentArray = $Cobj->union($sql);
两个查询结果相同的输出。但是意志是一种有效的方法吗?
【问题讨论】:
-
第一个是有效的方法
-
@Rahautos :请说一下如何以及为什么?
-
第一个可能更有效,因为您让 SQL 服务器完成所有优化工作并且您只查询一次(与 php 的交互较少)。但是您可能应该在查询中使用
union all,因为标准的union会隐含地抛出distinct子句,这可能会再次减慢速度。 -
因为在第一种情况下,您执行一个 MySQL 查询。@VigneswaranS
标签: php mysql sql-server