联合查询中的MySql链接表

时间:2015-04-29 08:00:23

标签: mysql

我需要从联合查询中选择一些特定的总和到3个应该为
的表 在列字段中可用,但我看到错误 错误代码:1054。'where子句'中的未知列'm.Id' 看起来联合子查询中的M.id看起来不可见。我如何才能使它工作,没有功能,只能通过查询。

SELECT
    m.COL1,
    m.COL2,
    p.Id,
    (
        SELECT 
            sum(cp) 
        FROM (
                SELECT 
                     count(*) as cp 
                FROM 
                     T1 as o
                WHERE 
                     o.st = 4 
                     AND o.LId = m.Id

                UNION ALL

                SELECT 
                     count(*) as cp 
                FROM 
                     T2 as oh
                WHERE 
                     oh.st = 0 
                     AND oh.LId = m.Id

                UNION ALL

                SELECT 
                    count(*) as cp 
                FROM 
                    T3 as os
                WHERE
                    os.st = 4 
                    AND os.LId = m.Id

            ) as PP 
        ) as IsFB

    FROM 
        TM as m
        JOIN TME as mx ON m.Id = mx.MId
        JOIN TP as p ON m.CID = p.PID

1 个答案:

答案 0 :(得分:1)

如果没有提供关于你想要什么的更多信息,很难回答

但是,首先在子查询中进行连接,例如:

            SELECT 
                 TM.COL1, TM.COL2, TM.id, count(*) as cp 
            FROM 
                 T1
            JOIN 
                 TM
            ON   
                 T1.LId = TM.id
            GROUP BY 
                 TM.COL1, TM.COL2, TM.id

然后,您将能够在外部查询中加入此内容,例如

SELECT
    UU.COL1,
    UU.COL2,
    TP.ID,
    sum(UU.cp)
FROM (
  ** union query goes here
) UU
JOIN TP ON UU.id = TP.PID
GROUP BY 
  UU.COL1, UU.COL2, TP.ID