问题:如何在将两个表连接在一起时覆盖两个表的值,并在需要时添加列?
逻辑
以下是我正在使用的表格的简单结构。
基础产品(表1)
+----+------------+-----------+-------+ | id | product_id | name | price | +----+------------+-----------+-------+ | 1 | p190x4 | Product 1 | 50 | | 2 | px180i | Product 2 | 50 | | 3 | zz9980 | Product 3 | 50 | | 4 | zz9212 | Product 4 | 50 | | 5 | tu8uii | Product 5 | 50 | +----+------------+-----------+-------+
子产品(表2)
+----+------------+-------+----------+ | id | product_id | price | location | +----+------------+-------+----------+ | 1 | p190x4 | 34 | NA | | 2 | px180i | 17 | RU | | 4 | zz9212 | 65 | LA | +----+------------+-------+----------+
通缉结果
+----+------------+-----------+-------+----------+ | id | product_id | name | price | location | +----+------------+-----------+-------+----------+ | 1 | p190x4 | Product 1 | 34 | NA | | 2 | px180i | Product 2 | 17 | RU | | 4 | zz9212 | Product 4 | 65 | LA | +----+------------+-----------+-------+----------+
在想要的结果中,您可以看到发生了一些事情。
name
列为added
。location
列为added
。price
列为updated
。修改
列名称是动态的。子产品表需要灵活,我可以轻松添加属性(列)或删除属性(列)。
答案 0 :(得分:1)
通常只需在SELECT列表中指定一个希望检索的列(在名称冲突的情况下根据需要使用表限定符):
SELECT t1.id, product_id, t1.name, t2.price, t2.location
FROM t1 JOIN t2 USING (product_id);
在sqlfiddle上查看。
如果提前不知道模式,可以从信息模式动态构造必需的SQL。例如,在MySQL中做整件事(这不是我的第一选择,但由于你没有指定开发应用程序的语言或API,它就足以显示一般原则):
SELECT CONCAT(
-- the SQL that we are constructing for subsequent execution
' SELECT ',GROUP_CONCAT(
'`',REPLACE(t,'`','``'),'`.`',REPLACE(c,'`','``'),'`'
ORDER BY t, p
),
' FROM t1 JOIN t2 USING (product_id)'
) INTO @sql FROM (
-- the table-qualified column references that we wish to select
SELECT MAX(TABLE_NAME) t, -- MAX because 't2'>'t1'
COLUMN_NAME c,
ORDINAL_POSITION p
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME IN ('t1','t2')
GROUP BY COLUMN_NAME
) t;
-- prepare the statement for execution
PREPARE stmt FROM @sql;
-- execute it
EXECUTE stmt;
-- tidy up
DEALLOCATE PREPARE stmt;
SET @sql := NULL;
在sqlfiddle上查看。
答案 1 :(得分:0)
使用别名并限定要输出的字段:
SELECT s.id, p.product_id AS product_id, p.name , s.price AS price , s.location
FROM product p
INNER JOIN sub_product s ON (s.product_id = p.product_id)
已更新(product_id
而不是id
)