我有两张桌子:
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');
答案 0 :(得分:3)
在日期列上创建一个键,然后使用INSERT IGNORE
或INSERT ... ON DUPLICATE KEY UPDATE
语法。有关详情,请参阅此处:"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
此外,您可以使用触发器或过程而不是cron作业;可能会让生活变得更轻松。
答案 1 :(得分: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);