我有这个问题,应该向人们退还过去一周他们购买的东西的一半:
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以及他们在那一周花费的金额)。但是整个查询会抛出一个错误,说我在第2行附近的SQL语法中有错误(我引用:'FROM main_data AS md INNER JOIN(SELECT DISTINCT sb.forum_id,SUM(sb.s')。
我看不出我做错了什么。
答案 0 :(得分: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)
答案 1 :(得分:0)
INNER JOIN中没有user_Id
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