mySQL:将一个结果中的3个表中的数据与一个查询语句合并

时间:2016-05-18 18:32:16

标签: mysql sql

要在一个查询中合并来自invoiceclients表的发票和相应客户地址数据,我使用以下语句:

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] 
      }
   }

换句话说,在每个数组中,我从表all columnsinvoice中包含冗余内容的参与表中获取clients

如何仅将clients1 col的列分隔?

或者甚至更好地保存资源并仅收到来自invoice_items的发票和附件中的*的1个数组,所以它可能如下所示:

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] 
                  }
          }
 }

1 个答案:

答案 0 :(得分:1)

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