Mysql SELECT ... WHERE IN(从多个表中选择多个子项)

时间:2019-06-09 15:40:16

标签: mysql

mysql需要从一个表中获取数据,其中id与另一表中的列值相同。但是必须从另一个表中仅获取列值,其ID与其他两个表中的列值相同(IN)。

表如下:

带有列的表名sales_invoices(在下面我没有显示所有列,有一些列是问题所必需的)。
IdInvoices | Date

带有列的表名purchase_invoices
IdInvoicesP | Date

带有列的表名items
IdI | IdGoodsServices | IdInvoices

带有列的表名goods_services
IdGs(唯一值)

这是表格之间的链接
IdGs = IdGoodsServices
 IdInvoicesitems)= IdInvoicessales_invoices)= IdInvoicesP

尝试了多种代码变体。在所有情况下,都会出错。下面是最后使用的代码。

SELECT count(DISTINCT `IdGs`) FROM `goods_services` WHERE `IdGs` IN 

  ( SELECT `IdGoodsServices` FROM `items` WHERE `IdInvoices` IN 

    ( SELECT `IdInvoices`, `IdInvoicesP` FROM 
    `sales_invoices`, `purchase_invoices` WHERE `Date` <= ? ) 

  )  

要计算在特定日期之前发出(书写)的销售和购买发票中包含的IdGs(产品或商品/服务代码)。

goods_servicessales_invoices / purchase_invoices之间没有直接链接。表items链接到goods_services和(sales_invoices / purchase_invoices

上面的代码出现错误
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'Date' in where clause is ambiguous

尝试过的子-子只能从一张表中选择,得到一些结果且没有错误。
这是查询

SELECT count(DISTINCT `IdGs`) FROM `goods_services` WHERE `IdGs` IN 

  ( SELECT `IdGoodsServices` FROM `30u2s5r_items` WHERE `IdInvoices` IN 

    ( SELECT `IdInvoicesP` FROM 
    `30u2s5r_purchase_invoices` WHERE `Date` <= ? ) 

  )  

下面是工作代码(根据我到目前为止的测试)。

SELECT count(DISTINCT `IdGs`) FROM `goods_services` WHERE `IdGs` IN 

 (SELECT `IdGoodsServices` FROM `items` WHERE 

 `IdInvoices` IN 

  (SELECT DISTINCT `IdInvoices` FROM `sales_invoices` 
  WHERE `sales_invoices`.`Date` <= ? ) 

   OR 

  `IdInvoices` IN 
  ( SELECT DISTINCT `IdInvoicesP` FROM `purchase_invoices` 
  WHERE `purchase_invoices`.`Date` <= ? ) 

)

1 个答案:

答案 0 :(得分:1)

使用Purchase_invoices.Date或sales_invoices.Date