简体   繁体   English

从多个表中选择行

[英]Selecting rows from multiple tables

I would like to know what the fastest way is to make the following SQL call using PHP. 我想知道最快的方法是使用PHP进行以下SQL调用。 I am using procedural mySQLi. 我正在使用过程性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';
}

Is there a way to make the execution faster than like this, maybe to echo the results from both queries after the first if statement? 有没有一种方法可以使执行速度比这样快,也许可以在第一个if语句之后回显两个查询的结果?

It just seems rather long to me. 对我来说似乎很长。

Thanks in advance. 提前致谢。

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

Not tested, but something like it should work 未经测试,但类似的东西应该工作

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;

is what you need for multiple tables 您需要多个表

$row['d_max_id']

will give you deposits.max(id) now 现在会给您deposits.max(id)

You have to edit the d.id = a.id accordingly to what you want the two tables to match on 您必须根据希望两个表匹配的内容来编辑d.id = a.id

If you cant join try this: 如果您不能加入,请尝试以下操作:

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