2012-03-14 70 views
2

我有了這個查詢應該退還一半的人,他們在過去一週買東西:SQL查詢錯誤,需要一些幫助

UPDATE main_data SET md.amount_current = md.amount_current + (bought.total/2) 
FROM main_data AS md 
INNER JOIN (
    SELECT DISTINCT sb.user_id, SUM(sb.spend) AS total 
    FROM shopitems_bought AS sb 
    LEFT JOIN shopitems AS si 
    ON sb.shopitem_id = si.id 
    WHERE sb.date_bought <= '2012-03-09' 
    AND sb.date_bought > DATE_ADD('2012-03-09', INTERVAL -7 DAY) 
    AND si.valid = 1 
    GROUP BY sb.user_id 
) AS bought ON bought.user_id = md.user_id 
WHERE md.valid = 1 

SELECT部分​​執行它自己就好了,並返回正確的數據(應該退還的ID和他們在那周花費的金額)。然而,作爲一個整體的查詢拋出一個錯誤,說我的SQL語法附近第2行有一個錯誤(我引用:'FROM main_data AS md INNER JOIN(SELECT DISTINCT sb.forum_id,SUM(sb.s')。

我看不到我在做什麼錯

回答

3

MySql uses a different syntax for join with update statements比你上面使用的是什麼試着改變你的查詢:。

UPDATE main_data md 
INNER JOIN (
    SELECT DISTINCT sb.user_id, SUM(sb.spend) AS total 
    FROM shopitems_bought AS sb 
    LEFT JOIN shopitems AS si 
    ON sb.shopitem_id = si.id 
    WHERE sb.date_bought <= '2012-03-09' 
    AND sb.date_bought > DATE_ADD('2012-03-09', INTERVAL -7 DAY) 
    AND si.valid = 1 
    GROUP BY sb.user_id 
) bought ON bought.user_id = md.user_id 
SET amount_current = md.amount_current - (bought.total/2) 
WHERE md.valid = 1 

注意,我改變

SET amount_current = md.amount_current + (bought.total/2) 

Ť Ø減去添加而不是:

SET amount_current = md.amount_current - (bought.total/2) 
+0

謝謝,解決它!所有這些不同的SQL版本都很煩人。 – Clavus 2012-03-14 22:44:28

0

沒有user_Id內內JOIN

UPDATE main_data SET md.amount_current = md.amount_current + (bought.total/2) 
FROM main_data AS md 
INNER JOIN (
    SELECT sb.user_id, DISTINCT sb.forum_id, SUM(sb.spend) AS total 
    FROM shopitems_bought AS sb 
    LEFT JOIN shopitems AS si 
    ON sb.shopitem_id = si.id 
    WHERE sb.date_bought <= '2012-03-09' 
    AND sb.date_bought > DATE_ADD('2012-03-09', INTERVAL -7 DAY) 
    AND si.valid = 1 
    GROUP BY sb.user_id 
) AS bought ON bought.user_id = md.user_id 
WHERE md.valid = 1 
+0

哦,等等,這是我的不好,我有點混淆了實際的代碼。 sb.forum_id應該是sb.user_id – Clavus 2012-03-14 22:39:23

+0

@Clavus,以[sqlfiddle](http://sqlfiddle.com)創建一個你的問題的演示, – Starx 2012-03-14 22:41:13