【问题标题】:Is there a solution for finding SQL Query with join of 3 tables and do some opperations in a period?有没有一种解决方案可以在一段时间内查找连接 3 个表并进行一些操作的 SQL 查询?
【发布时间】:2026-01-11 03:45:01
【问题描述】:

有没有办法通过连接 3 个表来查找 SQL Query 并在一段时间内执行一些操作? 如下查询:

https://i.stack.imgur.com/SpWkt.png

SELECT ST.code,ST.Plant,ST.STINT,E.code,E.Plant,SUM(E.Quantite) AS E_Qte,S.code,S.Plant,S.S_Qte 
    FROM `enter` E 
    INNER JOIN (SELECT code,Plant,SUM(Quantite) AS S_Qte FROM `sortie` group by code,Plant) S 
    INNER JOIN 
    (SELECT code,plant,sum(stockinitiale) AS STINT 
    FROM `stockinitiale` group by code,Plant) ST ON E.Code= S.Code=ST.Code AND E.Plant= S.Plant=ST.Plant 
    WHERE date BETWEEN '2019-05-17' AND '2019-05-28' 
    GROUP BY E.code,S.code,ST.code,E.Plant,S.Plant,ST.Plant

预期输出:

+------+-------+-------+------+-------+-------+------+-------+--------+
| code | Plant | STINT | code | Plant | E_Qte | code | Plant | S_Qte  |
+------+-------+-------+------+-------+-------+------+-------+--------+
| 1001 | P1    |   122 | 1001 | P1    |   662 | 1001 | P1    |     19 |
| 1001 | P3    |   108 | 1001 | P3    |    10 | 1001 | P3    |      2 |
| 1002 | P1    |     0 | 1002 | P1    |     4 | 1002 | P1    |     15 |
| 1002 | P3    |     6 | 1002 | P3    |     7 | 1002 | P3    |     12 |
| 1008 | P1    |    12 | 1001 | P1    |    66 | 1001 | P1    |     17 |
+------+-------+-------+------+-------+-------+------+-------+--------+

【问题讨论】:

  • 这是 E.Plant= S.Plant=ST.Plant 上的错字吗?并且您的第一次加入需要一个 on 子句
  • 首先感谢您的评论。此查询有效,但是当我添加 E.code= S.code=ST.code 时,我得到了空显示!

标签: mysql sql sql-server phpmyadmin


【解决方案1】:

我没有检查其他任何东西,只是为了你加入的情况你可以试试这个......

    SELECT ST.code,ST.Plant,ST.STINT,E.code,E.Plant,sum(E.Quantite) AS E_Qte,S.code,S.Plant,S.S_Qte
    FROM enter E 
    INNER JOIN 
    (SELECT code,Plant,sum(Quantite) As S_Qte FROM sortie group by code,Plant) S ON E.Plant= S.Plant
    INNER JOIN 
    (SELECT code,plant,sum(stockinitiale) AS STINT FROM stockinitiale group by code,Plant) ST on S.Plant=ST.Plant 
    where date between '2019-05-17' and '2019-05-28' group by E.code,S.code,ST.code,E.Plant,S.Plant,ST.Plant

虽然最好发布您的输入和预期输出,但如果这不适合您的情况。

【讨论】:

  • 请检查我的预期输出
最近更新 更多