简体   繁体   English

如何在mysql中具有外键属性的表中插入新记录

[英]how to insert a new record in a table that has foreign key attributes in mysql

What is wrong in this statement since customers table has only one record 此语句有什么问题,因为客户表只有一个记录

INSERT INTO CART (Cartid,custid,Pid)
VALUES ('2',SELECT(custid from CUSTOMERS), SELECT (Pid from Products where Pname ='shirts'))

The correct syntax is: 正确的语法是:

INSERT INTO CART (Cartid, custid, Pid)
    VALUES (2,
            (SELECT custid FROM CUSTOMERS LIMIT 1),
            (SELECT Pid FROM Products WHERE Pname = 'shirts' LIMIT 1)
           );

Your parentheses are in the wrong place. 您的括号放在错误的位置。

Notes: 笔记:

  • I added the LIMIT just to enforce that one row is returned. 我添加了LIMIT只是为了强制返回一行。
  • I removed the single quotes around '2' , because ids are usually number. 我删除了'2'周围的单引号,因为id通常是数字。
  • You probably should not be inserting the id; 您可能不应该插入ID。 it should be an auto-increment column. 它应该是一个自动增量列。

Make sure that the cart table id is primary key and auto_increment. 确保购物车表ID是主键和auto_increment。 Get the customer id and store in a variable. 获取客户ID并将其存储在变量中。 You can try something similar like this 您可以尝试类似的事情

INSERT INTO CART (Cartid,custid,Pid) VALUES ('', SELECT custid from CUSTOMERS  WHERE custid = '$customer_id'),(SELECT Pid FROM Products WHERE Pname = 'shirts' LIMIT 1));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM