MySQL加入查询问题

时间:2013-04-26 07:33:27

标签: mysql join

我正在尝试加入两个不同的查询。每个查询单独工作但在加入时不起作用。

SELECT * 
    FROM (


    SELECT i.id AS wid, i.start_time, i.end_time, i.drawing_time, i.result, SUM( t.amount ) AS wpAmount, SUM( t.prize ) , COUNT( t.id ) AS cntWinTickets
    FROM issues i
    LEFT JOIN orders o ON o.issue_id = i.id
    LEFT JOIN tickets t ON t.order_id = o.id
    AND t.has_prize =1
    GROUP BY i.id
    ) AS A
    JOIN 
    SELECT * 
    FROM (

SELECT i.id AS lid, SUM( t.amount ) AS lpAmount, COUNT( t.id ) AS cntLoosTickets
FROM issues i
LEFT JOIN orders o ON o.issue_id = i.id
LEFT JOIN tickets t ON t.order_id = o.id
AND t.has_prize !=1
GROUP BY i.id
) AS B ON A.wid = B.lid

内部查询工作正常,但加入后无效。

以下是错误消息:

MySQL说:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT * FROM (
SELECT i.id as lid, SUM( t.amount ) AS lpAmount , COUNT( t.id )' at line 12

2 个答案:

答案 0 :(得分:2)

试试这个(在SELECT之后删除不必要的JOIN):

SELECT * 
    FROM 
    (
    SELECT i.id AS wid, i.start_time, i.end_time, i.drawing_time, i.result, SUM( t.amount ) AS wpAmount, SUM( t.prize ) , COUNT( t.id ) AS cntWinTickets
    FROM issues i
    LEFT JOIN orders o ON o.issue_id = i.id
    LEFT JOIN tickets t ON t.order_id = o.id
    AND t.has_prize =1
    GROUP BY i.id
    ) AS A
    JOIN
    (
    SELECT i.id AS lid, SUM( t.amount ) AS lpAmount, COUNT( t.id ) AS cntLoosTickets
    FROM issues i
    LEFT JOIN orders o ON o.issue_id = i.id
    LEFT JOIN tickets t ON t.order_id = o.id
    AND t.has_prize !=1
    GROUP BY i.id
    ) AS B ON A.wid = B.lid

答案 1 :(得分:2)

尝试删除嵌套的SELECT *

SELECT *
FROM   (SELECT i.id          AS wid,
               i.start_time,
               i.end_time,
               i.drawing_time,
               i.result,
               Sum(t.amount) AS wpAmount,
               Sum(t.prize),
               Count(t.id)   AS cntWinTickets
        FROM   issues i
               LEFT JOIN orders o
                      ON o.issue_id = i.id
               LEFT JOIN tickets t
                      ON t.order_id = o.id
                         AND t.has_prize = 1
        GROUP  BY i.id) AS A
       JOIN (SELECT i.id          AS lid,
                    Sum(t.amount) AS lpAmount,
                    Count(t.id)   AS cntLoosTickets
             FROM   issues i
                    LEFT JOIN orders o
                           ON o.issue_id = i.id
                    LEFT JOIN tickets t
                           ON t.order_id = o.id
                              AND t.has_prize != 1
             GROUP  BY i.id) AS B
         ON A.wid = B.lid