SQL语法(具有多个外键的INSERTS)

时间:2010-11-22 02:06:30

标签: sql mysql select insert

如果我想在查找外键时插入记录,我可以这样做:

INSERT INTO stores_products (name, product_id)
SELECT 'storeABC',
       id 
  FROM products 
 WHERE name = 'product123';

(其中product_id是products表的外键)

但是,当我需要从多个表中查找外键时,我无法弄清楚语法。

例如,我想做类似的事情:

INSERT INTO stores_products 
  (name, product_id, owner_id)
SELECT 'storeABC', products.id, owners.id 
 FROM products 
WHERE name = 'product123' 
 FROM owners 
WHERE name = 'owner456';

(表名和列名只是一个例子,我知道从数据库设计的角度来看它没有多大意义,但我的问题是关于语法...)。感谢。

3 个答案:

答案 0 :(得分:5)

如果产品和所有者记录之间没有关系,请使用:

INSERT INTO STORE_PRODUCTS
  (name, product_id, owner_id)
SELECT 'storeABC',
       p.id,
       (SELECT o.id
          FROM OWNERS o
         WHERE o.name = 'owner456')
  FROM PRODUCTS p
 WHERE p.name = 'product123'

否则,如果OWNERS和PRODUCTS表之间存在关系 - 您可以使用JOIN指定它:

INSERT INTO STORE_PRODUCTS
  (name, product_id, owner_id)
SELECT 'storeABC',
       p.id,
       o.id           
  FROM PRODUCTS p
  JOIN OWNERS o ON o.relation_to_product_col = p.relation_to_owner_col
 WHERE p.name = 'product123'
   AND o.name = 'owner456'

参考:

答案 1 :(得分:1)

如果[products.name]和[owners.name]是唯一的,您可以使用关键字交叉加入进行笛卡尔联接。结果将是包含您要查找的ID的一行。

insert 
  into stores_products(name, product_id, owner_id)
select 'storeABC' as name
       ,products.id
       ,owners.id 
 from products cross join owners
where products.name = 'product123' 
  and owners.name   = 'owner456';

答案 2 :(得分:0)

尝试这样做:

更新

INSERT INTO stores_products 
  (name, product_id, owner_id)
SELECT 'storeABC', 
       products.id, 
       owners.id 
  FROM products, owners 
    WHERE products.name = 'product123' 
AND WHERE owners.name = 'owner456';