我计划在产品价格低于目标价格时通知用户价格警报系统。在某些情况下,我只能将主流和二手零售商的价格存储在两个单独的表中。我可能无法在不久的将来更改它,所以如果这可能会使问题复杂化,请原谅我。为了在商家的价格(无论是主流还是二手)达到用户的目标价格区域时通知用户,我需要在表 price_alert
中插入一条记录,其值为 entry_id
, user_id
,merchant_id
和 lowest_price
。
这是我的问题。我可以在一个语句中分别从表 mainstream
和 secondhand
插入记录到 price_alert
吗?
我期望的输出应该是这样的:
ENTRY_ID USER_ID MERCHANT_ID LOWEST_PRICE Is_read
1 1 3 100 0
3 2 1 300 0 // Merchant 3 is a second hand store while Merchant 1 is a mainstream store.
此代码无法运行,因为它只能从 mainstream_retailer_price
获取价格
INSERT INTO price_alert (entry_id,user_id,merchant_id,lowest_price)
SELECT
u.entry_id,mrp.merchant_id,u.user_id,mrp.price
FROM
user_target_price u
INNER JOIN mainstream_retailer_price mrp
ON u.product_id = mrp.product_id
INNER JOIN second_hand_retailer_price shrp
ON u.product_id = shrp.product_id
WHERE
(u.target_low_price > mrp.price)
OR u.target_low_price > shrp.price
GROUP BY u.entry_id
我能做点什么吗:
SELECT
u.entry_id,(mrp.merchant_id OR shrip.merchant_id),u.user_id,(mrp.price OR shrp.price)
表架构:
CREATE TABLE mainstream_retailer_price
(`id` int, `merchant_id` int,`product_id`int,`price` int)
;
INSERT INTO mainstream_retailer_price
(`id`,`merchant_id`,`product_id`,`price`)
VALUES
(1,1,1,200),
(2,1,2,300),
(3,2,1,150)
;
CREATE TABLE second_hand_retailer_price
(`id` int, `merchant_id` int,`product_id` int, `price` int)
;
INSERT INTO second_hand_retailer_price
(`id`,`merchant_id`,`product_id`,`price`)
VALUES
(1,3,1,100),
(2,3,2,600)
;
CREATE TABLE user_target_price
(`entry_id` int,`user_id` int, `target_low_price` int,`product_id` int)
;
INSERT INTO user_target_price
(`entry_id`,`user_id`,`target_low_price`,`product_id`)
VALUES
(1,1,150,1),
(2,1,200,2),
(3,2,350,2)
;
CREATE TABLE merchant
(`merchant_id` int, `merchant` varchar(20))
;
INSERT INTO merchant
(`merchant_id`,`merchant`)
VALUES
(1,'First Hand A'),
(2,'First Hand B'),
(3,'Second Hand A')
;
CREATE TABLE price_alert
(`entry_id` int, `user_id` int,`merchant_id` int,`lowest_price` int,`is_read` int)
;
最佳答案
似乎您可能想使用 UNION 将表中的 SELECT 和 INSERT 合并为一个。这是基本的查询结构。您执行 2 个选择,将结果与 UNION 组合,该 UNION 上的 SELECTin 用于 INSERT。您的字段名称需要在内部 SELECT 上完全相同。
INSERT INTO price_alert (entry_id,user_id,merchant_id,lowest_price)
SELECT * FROM (
SELECT ... FROM user_target_price u INNER JOIN mainstream_retailer_price mrp ...
UNION
SELECT ... FROM user_target_price u INNER JOIN second_hand_retailer_price srp ...
) AS rp
关于html - 在mysql中分别从另外两个表插入行到一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25413101/