[英]How to JOIN data from query with list of data?
Two tables with some data in the second one. 两个表,第二个表中包含一些数据。
CREATE TABLE IF NOT EXISTS dst (
id integer NOT NULL,
content varchar(200) NOT NULL);
CREATE TABLE IF NOT EXISTS src (
id integer NOT NULL,
name varchar(200) NOT NULL);
INSERT INTO src VALUES('100', 'ET'), ('200', 'Luke'), ('300', 'Jojo');
Now, I insert one selected id from src and some other list of values. 现在,我从src插入一个选定的ID以及其他一些值列表。 So the result should look like this:
因此结果应如下所示:
200, one
200, two
200, three
And this is my try of 这是我的尝试
INSERT INTO dst (id, content)
SELECT * FROM ((SELECT id FROM src WHERE name = 'Luke') AS bar
CROSS JOIN ('one', 'two', 'three')) AS foo;
The issue is how can I put the second argument for JOIN - ('one', 'two', 'three'), because this way doesn't work. 问题是我该如何为JOIN输入第二个参数-(“一个”,“两个”,“三个”),因为这种方式行不通。
ERROR: syntax error at or near "'one'"
Use UNION ALL
(in your case you didn't alias the column of the second subquery. eg as content
, and comma seperated strings ('one','two','three')
will not work, should be converted to a query ) 使用
UNION ALL
(在您的情况下,您没有为第二个子查询的列添加别名。例如, as content
,逗号分隔的字符串('one','two','three')
不起作用,应将其转换为查询)
INSERT INTO dst (id, content)
SELECT bar.id, foo.content
FROM
(
( SELECT id FROM src WHERE name = 'Luke' ) as bar
CROSS JOIN
(
SELECT 'one' as content UNION ALL
SELECT 'two' UNION ALL
SELECT 'three'
) as foo
)
An alternative solution is to use unnest()
- this will convert an array into rows: 另一种解决方案是使用
unnest()
-这会将数组转换为行:
select
unnest(array['one', 'two', 'three']::varchar[]) as content
Would yield 会屈服
content (varchar)
---------------
one
two
three
This is implicitly cross joined when used in a select statement: 在select语句中使用时,这是隐式交叉连接的:
insert into dst (
id,
content
) (
select
src.id,
unnest(array['one', 'two', 'three']::varchar[])
from
src
where
src.name = 'Luke'
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.