【问题标题】:Insert one value into a table with all values from another table将一个值插入到包含另一个表中的所有值的表中
【发布时间】:2021-10-17 01:46:41
【问题描述】:
INSERT INTO inventory (film_id, store_id)
VALUES ((SELECT film_id FROM film WHERE title='EUCLIDEAN PI'), (SELECT store_id from store));

这不起作用。返回的错误是“作为表达式的子查询返回了不止一行”。

基本上,我的库存应该为每家商店都有这部特定电影的副本。如果 ECULIDEAN PI 的 id 是 347。inventory 表应该为 store 表中的每个 store_id 显示 347 的副本。

film_id store_id  
347     1  
347     2  
347     3  
347     n

其中 n 是最后一个 store_id。 Store_id 可能并不总是递增的。

【问题讨论】:

  • 你用的是什么数据库?
  • 我正在使用 postgresql

标签: sql postgresql sql-insert


【解决方案1】:

您没有提及您使用的是哪个特定数据库,并且它们之间的语法略有变化。

我假设它适用于 SQL Server。如果是这种情况,您可以这样做:

insert into inventory (film_id, store_id)
select
  (select film_id from film where title = 'EUCLIDEAN PI'), 
  store_id
from store;

结果:

 film_id  store_id 
 -------- -------- 
 347      1        
 347      2        
 347      3        
 347      7        
 347      10       

请参阅db<>fiddle 的运行示例。

【讨论】:

  • 我正在使用 postgresql。这还能用吗?
  • @INeedHelp101 是的,我在小提琴中将下拉列表更改为“PostgreSQL”,它按预期工作。见dbfiddle.uk/…
猜你喜欢
  • 2010-10-09
  • 2012-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2014-07-29
相关资源
最近更新 更多