在PHP中顺序查询多个MSSQL表中的一个值

问题描述

| 我有2个表需要查询单个结果,但是如果在$ table0中找到它,则需要停止搜索并使用该行中的值。像这样:
$p1_sql = \"SELECT TOP 1 * FROM \'$table0\' WHERE phone1 = \'$cidnumber\'\";
$p2_sql = \"SELECT TOP 1 * FROM \'$table0\' WHERE phone2 = \'$cidnumber\'\";
$c1_sql = \"SELECT TOP 1 * FROM \'$table1\' WHERE contactphone = \'$cidnumber\'\";
$c2_sql = \"SELECT TOP 1 * FROM \'$table1\' WHERE contactphone2 = \'$cidnumber\'\";
$c3_sql = \"SELECT TOP 1 * FROM \'$table1\' WHERE contactphone3 = \'$cidnumber\'\";
$c4_sql = \"SELECT TOP 1 * FROM \'$table1\' WHERE contactphone4 = \'$cidnumber\'\";

$p1_res = mssql_query($p1_sql);
$p1_row = mssql_num_rows($p1_res);

$p2_res = mssql_query($p2_sql);
$p2_row = mssql_num_rows($p2_row);

$c1_res = mssql_query($c1_sql);
$c1_row = mssql_num_rows($c1_res);

$c2_res = mssql_query($c2_sql);
$c2_row = mssql_num_rows($c2_res);

$c3_res = mssql_query($c3_sql);
$c3_row = mssql_num_rows($c3_res);

$c4_res = mssql_query($c4_sql);
$c4_row = mssql_num_rows($c4_res);

if ($p1_row = 1){
    $p1_res = $newres;
    goto okres;
} elseif ($p2_row = 1) {
    $p2_res = $newres;
    goto okres;
} elseif ($c1_row = 1) {
    $c1_res = $newres;
    goto okres;
} elseif ($c2_row = 1) {
    $c2_res = $newres;
    goto okres;
} elseif ($c3_row = 1) {
    $c3_res = $newres;
    goto okres;
} elseif ($c4_row = 1) {
    $c4_res = $newres;
    goto okres;
} else {
    $newres = \"na\";
    goto nares;
}

okres:
$cid_sel = mssql_query(\"SELECT TOP 1 * FROM \'$table0\' WHERE phone1 = \'$cidnumber\'\");
但是,这很丑陋,不起作用。我试图使用\'for each ... \'或\'while(something)\',但无法绕开它的工作原理。我什至不知道会不会。最好的方法是什么?这是我第一次涉足此类问题,我们将不胜感激。     

解决方法

我将不同的查询添加到数组中并循环(使用foreach)该数组以随后查询数据库。一旦找到要查找的内容,就会使用break中断循环;命令。 在纯sql中使用联接也可能是一种解决方案,但是我不完全确定您希望在这里实现什么。 祝好运!     ,不必执行很多单独的查询。您是否熟悉基本的SQL,以及JOIN和UNION?如果不是,您应该阅读它们-只需一个查询就可以实现此处想要的功能。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...