0

我有两张桌子:

purchase_mis(id, user_id, total_purchased, date)
daily_purchase(id, user_id, product_id, paid_amount, purchase_date)

我有一个每天晚上运行的 CRON 文件,它计算"daily_purchase"表中的每日购买量并运行insert into "purchase_mis".

例如:

SELECT
    COUNT(*) AS purchase_count,
    purchase_date
FROM daily_purchase
GROUP BY user_id;

purchase_count将为每个用户返回 ,然后将其插入到"purchase_mis"表中。

INSERT INTO
    purchase_mis(user_id, total_purchased, date)
VALUES
    ('2', 'purchase_count', 'purchase_date');

但是在插入之前,需要检查user_id = 2某个日期“ purchase_date”的购买信息是否已经插入,所以不要再次插入。


我想要类似下面的查询:

INSERT INTO
    purchase_mis(user_id, total_purchased, date)
VALUES
    ('2', 'purchase_count', 'purchase_date')
WHERE date NOT EXISTS (SELECT date FROM purchase_mis WHERE user_id = '2');
4

2 回答 2

3

在日期列上创建一个键,然后使用INSERT IGNOREorINSERT ... ON DUPLICATE KEY UPDATE语法。有关更多信息,请参见:“INSERT IGNORE”与“INSERT ... ON DUPLICATE KEY UPDATE”

此外,您可能可以使用触发器或过程来代替 cron 作业;可能会让生活更轻松一些。

于 2012-12-06T06:20:02.310 回答
0
insert into purchase_mis
   (user_id, total_purchased, date)
select * 
from (
   select 2 as id, 
          100 as user_id, 
          str_to_date('2012-12-04', '%Y-%m-%d') as purchase_date
) t 
where not exists (SELECT 1 
                  FROM purchase_mis pm
                  WHERE pm.user_id = t.id 
                  and pm.date = t.purchase_date);
于 2012-12-06T19:56:32.367 回答