2013-04-26 184 views
1

我想加入2個不同的查詢。每個查詢單獨工作,但在加入時不工作。問題MySQL聯合查詢

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 
+0

不工作怎麼樣? – sashkello 2013-04-26 07:34:53

+1

刪除第二個SELECT * FROM,這是加入後 - 你不需要它... – sashkello 2013-04-26 07:35:30

+0

@sashkello:檢查更新的問題PLZ。 – 2013-04-26 07:37:59

回答

2

嘗試此(JOIN之後除去不必要的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 
+0

爲什麼downvote?說明。 – sashkello 2013-04-26 07:39:21

+1

+1,你的回答是對的,你不配得到downvote。 – 2013-04-26 07:44:48

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