简体   繁体   English

MySQLi:使用变量查询到另一个表

[英]MySQLi: Query with a variable to another table

So, I have a database with a few tables in it. 所以,我有一个包含几个表的数据库。 Most of these tables contain information about the same document and are connected by an ID (it's stupid since it could all be in the same table, but the company I'm helping out for can't change this right now). 这些表中的大多数都包含有关同一文档的信息,并且通过ID连接(它很愚蠢,因为它可能都在同一个表中,但我正在帮助的公司现在无法改变它)。 The content of the 2 tables that I'm currently working on can be seen below. 我目前正在处理的2个表的内容如下所示。

tblDocument: Contains ID + other info. tblDocument:包含ID +其他信息。

tblVerification: Contains ID, verificationNo + other info. tbl验证包含ID,verificationNo +其他信息。

Now, what I'd like to do is to find the verificationNo in tblVerification from the ID in tblDocument , using PHP and MySQLi. 现在,我想要做的就是从tblDocumentID找到tblVerificationverificationNo,使用PHP和库MySQLi。 I've found a solution that allows me to pass a variable into the query, but it doesn't feel like this is the most efficient solution and the code confuses me. 我找到了一个允许我将变量传递给查询的解决方案,但它不觉得这是最有效的解决方案而且代码让我感到困惑。 Any additional information about how the query works or a new simpler solution is greatly appreciated. 非常感谢有关查询如何工作或更简单的解决方案的任何其他信息。

<?php

$mysqli = new mysqli("ip", "name", "pw", "db");
$dbDoc = $mysqli->query("SELECT * FROM tblDocument ORDER BY ID");

while ($row = $dbDoc->fetch_assoc()) {
    $tempID = $row["ID"];

    $bind = 's';
    $queryThis = $mysqli->prepare("SELECT verificationNo FROM tblVerification WHERE ID = ?");
    $queryThis->bind_param($bind, $tempID);
    $queryThis->execute();
    $queryThis->bind_result($result);
    $queryThis->fetch();
    $queryThis->close();
    $tempVer = $result;

    echo $tempVer . " ";
}
?>

Actual question: Is this the most efficient way to achieve this result using only PHP and MySQLi and/or what can you do to simplify it? 实际问题:这是仅使用PHP和MySQLi实现此结果的最有效方法和/或您可以做些什么来简化它?

Have you try with join? 你试过加入吗?

"SELECT tblDocument.*, tblVerification.verificationNo
FROM tblDocument INNER JOIN tblVerification
    ON tblDocument.ID=tblVerification.id
ORDER BY ID"

You should use SQL JOIN in this case:- 在这种情况下,您应该使用SQL JOIN : -

Your query should be:- 您的查询应该是: -

"SELECT tblDocument.*, tblVerification.verificationNo
FROM tblDocument
LEFT JOIN tblVerification
ON tblDocument.ID = tblVerification.ID
ORDER BY tblDocument.ID;"

You can simply join the two tables: 您可以简单地加入两个表:

SELECT tv.id, tv.verificatioNo 
FROM tblVerification tv
INNER JOIN tblDocument td
ON tv.id = td.id
ORDER BY tv.id;

And if you want to filter for some particular id add the WHERE condition: 如果你想过滤一些特定的id添加WHERE条件:

WHERE tv.id = ? 

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

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