繁体   English   中英

从多个表中选择行

[英]Selecting rows from multiple tables

我想知道最快的方法是使用PHP进行以下SQL调用。 我正在使用过程性mySQLi。

$dcount = "SELECT max(id) FROM deposits";
$result = mysqli_query($conn,$dcount);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
    $count = $row["max(id)"];
    echo $count;
    echo ",";

}
} else {
echo '0';
}

//second query
$ucount = "SELECT max(int) FROM anothertable";
$result2 = mysqli_query($conn,$ucount);
if (mysqli_num_rows($result2) > 0) {
while($row = mysqli_fetch_assoc($result)) {
    $count = $row["max(int)"];
    echo $count;
    echo ",";

}
} else {
echo '0';
}

有没有一种方法可以使执行速度比这样快,也许可以在第一个if语句之后回显两个查询的结果?

对我来说似乎很长。

提前致谢。

SELECT max(id) as max_id, (SELECT max(int) as max_int FROM anothertable) as max_int
FROM deposits

未经测试,但类似的东西应该工作

SELECT d.max(id) as d_max_id, a.max(int) as a_max_int FROM deposits as d JOIN anothertable as a ON d.id = a.id;

您需要多个表

$row['d_max_id']

现在会给您deposits.max(id)

您必须根据希望两个表匹配的内容来编辑d.id = a.id

如果您不能加入,请尝试以下操作:

SELECT max(id) as max_id, (SELECT max(int) FROM anothertable) as max_int FROM deposits;

SELECT max(id) as max_id, max(int) as max_int FROM deposits ,anothertable

$dcount = "
SELECT max(id) as max,'deposit' as table_name FROM deposits
UNION
SELECT max(id) as max,'another' as table_name FROM anothertable
"; 

$result = mysqli_query($conn,$dcount);
if (mysqli_num_rows($result) > 0){
  while($row = mysqli_fetch_assoc($result)){
    echo $row["table_name"].":".$row["max"]."\n";
  }
} else {
  echo '0';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM