在mysql中分别从另外两个表中将行插入表中

时间:2014-08-20 19:38:45

标签: html mysql sql join insert

Fiddle Example

我计划在价格警报系统上在产品低于目标价格时通知用户。有些情况限制我存储主流和二手零售商'价格在两个单独的表中。我可能无法在不久的将来改变它,所以请原谅我,如果它可能使问题复杂化。要在商家的价格(无论是主流还是秒针)达到用户的目标价格区域时通知用户,我需要在表price_alert中插入一条记录值entry_iduser_idmerchant_idlowest_price。 这是我的问题。我可以在一个声明中分别从表price_alertmainstream中将记录插入second hand吗?

我的预期输出应该是这样的:

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)
;

1 个答案:

答案 0 :(得分:1)

好像您可能希望使用UNION从表和INSERT中选择一个。这是基本的查询结构。你做的2选择,结果与UNION,INSION的UNION上的SELECTin。您的字段名称必须在内部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