如何使用sql query ..联接“我的发票和发票产品”表?

时间:2019-05-02 10:28:28

标签: mysql sql

我有两个表格发票和发票产品表格,我想针对每个发票ID将我的两个表格结合起来。

我尝试编写sql查询,但这是错误的。

SELECT invoice.invoice_id, invoice_product.product_name
FROM invoice, invoice_product
WHERE invoice.invoice_id = invoice_product.invoices_id

我想显示我的实际结果。


Invoice_id | Invoice_name | Product_name                | Created Date
========== |============= |=============================|==============
   1       |    Test 1    |   Product1 ,product 2       | 2019-05-02
   2       |    Test 2    |    New Product ,New Product | 2019-05-02

invoice表:

enter image description here

invoice_product表:

enter image description here

3 个答案:

答案 0 :(得分:2)

您需要使用GROUP_CONCAT来获得类似的产品列表,并按发票编号分组。这将起作用:

SELECT i.invoice_id, i.invoice_name, GROUP_CONCAT(ip.product_name) AS products, i.created_at
FROM invoice i
JOIN invoice_product ip ON i.invoice_id = ip.invoices_id
GROUP BY i.invoice_id

输出:

invoice_id  invoice_name    products                        created_at
1           Test 1          Product 1,Product 2             2019-05-02 00:00:00
2           Test 2          Product New,Product New New     2019-05-02 00:00:00

Demo on dbfiddle

请注意,使用逗号的隐式JOIN语法已被弃用了一段时间,最好改写显式JOIN

答案 1 :(得分:1)

请避免与您的实际语法混淆,这太旧了。 我不建议使用非原子值,但是GROUP_CONCAT函数正在为您完成这项工作。

SELECT invoice.invoice_id, GROUP_CONCAT(IP.product_name), I.created_at
FROM invoice AS I
JOIN invoice_product AS IP
    ON I.invoice_id = IP.invoices_id
GROUP BY IP.invoices_id

答案 2 :(得分:0)

使用group_concat()

SELECT invoice.invoice_id, group_concat(invoice_product.product_name)
FROM invoice join  invoice_product
on invoice.invoice_id = invoice_product.invoices_id
group by invoice.invoice_id