要在一个查询中合并来自 invoice
和 clients
表的发票和相应的客户地址数据,我使用以下语句:
SELECT *
FROM invoice, clients
WHERE invoice.client_id = clients.ID
它工作完美。但是现在我有第三个表进入游戏,其中存储了 invoice_items。每张发票都有一项或多项将向客户收费的项目。每个 invoice_item UPDATE
存储相应的、先前生成的 invoice.ID。但是如何在一个查询中合并 3 个表呢?我这样试过:
SELECT *
FROM invoice, invoice_item, clients
WHERE inv_num =:num
AND invoice.client_id = clients.ID
AND invoice_item.inv_id = invoice.ID
但是到目前为止我还没有成功。我做错了什么?
感谢任何帮助。
编辑:整个语句如下所示:
$query = $this->db_con->prepare('SELECT * FROM invoice, invoice_item, clients WHERE inv_num =:num AND invoice.client_id = clients.ID AND invoice_item.inv_id = invoice.ID');
$query->bindValue(':num',$val, PDO::PARAM_STR);
$success = $query->execute();
$val 是之前从表格中选择的发票编号。
更新:
根据 Stivan 的回答,我得到了以下结果模式。 假设有 1 张发票和 2 个 invoice_item:
Array {
[0] => Array {
// col from table `invoice`
[col 1]
[col 2]
[col n]
// col from table `invoice_item`
[col 1]
[col 2]
[col n]
// col from table `clients`
[col 1]
[col 2]
[col n]
}
[1] => Array {
// col from table `invoice`
[col 1]
[col 2]
[col n]
// col from table `invoice_item`
[col 1]
[col 2]
[col n]
// col from table `clients`
[col 1]
[col 2]
[col n]
}
}
换句话说,在每个数组中,我从参与表中获取所有列
,其中表invoice
和clients
中有冗余内容。
如何将列从 clients
分隔为 1 col
?
或者甚至更好地保存资源并仅接收 1 个带有 * 来自发票和来自 invoice_items
的附加项目的数组,所以它可能看起来像这样:
Array {
[0] => Array {
// col from table `invoice`
[col 1]
[col 2]
[col n]
// col from table `clients`
[col 1]
}
Array {
[0] => Array {
// col from table `invoice_items`
[col 1]
[col 2]
[col n]
}
[1] => Array {
// col from table `invoice_items`
[col 1]
[col 2]
[col n]
}
}
}
最佳答案
select
*
from invoice
left join invoice_item on invoice_item.inv_id = invoice.ID
left join clients on clients.ID = invoice.client_id
where
invoice.inv_num = :num; //Or the table where inv_number comes from
corrected invoice.inv_number to invoice.inv_num
关于MySQL : merge data from 3 tables in one result with one query statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37307556/