오류 1452 MySQL 및 NodeJS.왜 데이터베이스가 내 테이블을 제대로 참조할 수 없는 거죠?
새 사용자 계정을 삽입할 때 노드 콘솔에서 오류 1452가 나타납니다.여기 오류가 있습니다.
{ 오류: ER_NO_REferenced_ROW_2: 하위 행을 추가하거나 업데이트할 수 없습니다. 외부 키 제약 조건이 실패합니다().
myeherlpertst2
.customers
, 제약사항customers_ibfk_1
외부 키(user_id
) 레퍼런스users
(user_id
))코드: 'ER_NO_REferenced_'ROW_2', errno: 1452, sqlMessage: '자 행을 추가하거나 업데이트할 수 없습니다. 외부 키 제약 조건이 실패합니다(
myeherlpertst2
.customers
, 제약사항customers_ibfk_1
외부 키(user_id
) 레퍼런스users
(user_id
)), sqlState: '23000', 인덱스: 0,
이 에러가 발생하는 이유는 고객 테이블이 존재하지 않는 것을 참조하려고 하는데 왜 참조하지 않는지 잘 모르겠습니다.아래 노드 코드에 먼저 사용자 테이블을 삽입합니다.이 테이블은 user_id가 자동으로 증가하며 늘이 아닙니다.고객 테이블에 삽입하기 전에 첫 번째 삽입에 대한 트랜잭션을 종료하고 새 삽입을 시작해야 합니까?
connection.beginTransaction(function(error){
if(error){
console.log('Error Caught');
return res;
}
if (error) {throw error;
console.log('Error Caught');
return;}
connection.query('Insert into users( user_name, user_password, user_type) values (?,?,?)', [customer.body.userName, customer.body.password, userType=1], function (error, results, fields) {
if (error) {
console.log(error);
return;
}
connection.query('Insert into customers(cust_first_name, cust_last_name, cust_email, cust_city, cust_address, cust_zip_code, cust_state, cust_phone_num, cust_role, cust_website, cust_business_name) values (?,?,?,?,?,?,?,?,?,?,?)', [customer.body.firstName, customer.body.lastName, customer.body.email, customer.body.city, customer.body.address, customer.body.zipCode, customer.body.state, customer.body.phoneNumber, customer.body.custRole=1, customer.body.website, customer.body.businessName], function (error, results, fields) {
if (error) {
console.log(error);
}
});
res.end(JSON.stringify(results));
});
console.log('End Transaction')
});
를 설정할 필요가 있습니다.user_id
의 컬럼이 바르게customers
테이블. MySQL의 LAST_INSERT_ID() 함수는 필요한 값의 소스입니다.SQL에서는 이 방법을 설명합니다.
Insert into users( user_name, user_password, user_type) values (?,?,?);
Insert into customers(user_id, cust_first_name, cust_last_name, cust_email,
cust_city, cust_address, cust_zip_code, cust_state,
cust_phone_num, cust_role, cust_website, cust_business_name)
values (LAST_INSERT_ID(),?,?,?,?,?,?,?,?,?,?,?);
고객 테이블에 삽입하면 LAST_INSERT_ID() 값이 해당 테이블의 자동 증분 ID 값으로 변경됩니다.따라서 사용자 테이블의 값을 재사용해야 할 경우 다음 두 가지 쿼리가 아닌 세 가지 쿼리를 사용하여 이 작업을 수행합니다.
Insert into users( user_name, user_password, user_type) values (?,?,?);
SET @userid := LAST_INSERT_ID();
Insert into customers(user_id, cust_first_name, cust_last_name, cust_email,
cust_city, cust_address, cust_zip_code, cust_state,
cust_phone_num, cust_role, cust_website, cust_business_name)
values (@userid,?,?,?,?,?,?,?,?,?,?,?);
노드 프로그램에 쿼리를 넣는 것은 당신에게 맡기겠습니다.
다른 쿼리는 필요 없습니다: 삽입 결과에 마지막 자동 증분 삽입 ID가 포함되어 있습니다.
이 정보는 results.insertId와 함께 제공됩니다.
따라서 수정은 다음과 같습니다.
connection.query(
"Insert into users( user_name, user_password, user_type) values (?,?,?)",
[customer.body.userName, customer.body.password, (userType = 1)],
function(error, results, fields) {
if (error) {
console.log(error);
return;
}
connection.query(
"Insert into customers(user_id, cust_first_name, cust_last_name, cust_email, cust_city, cust_address, cust_zip_code, cust_state, cust_phone_num, cust_role, cust_website, cust_business_name) values (?,?,?,?,?,?,?,?,?,?,?,?)",
[
results.insertId,
customer.body.firstName,
customer.body.lastName,
customer.body.email,
customer.body.city,
customer.body.address,
customer.body.zipCode,
customer.body.state,
customer.body.phoneNumber,
(customer.body.custRole = 1),
customer.body.website,
customer.body.businessName
],
function(error, results, fields) {
if (error) {
console.log(error);
}
}
);
res.end(JSON.stringify(results));
}
);
btw: userType=1 매개 변수는 오류일 수 있습니다.
언급URL : https://stackoverflow.com/questions/51293710/error-1452-mysql-and-nodejs-how-come-the-database-cant-reference-my-table-right
'programing' 카테고리의 다른 글
$_REQUEST, $_GET, $_POST 중 어느 것이 가장 빠릅니까? (0) | 2022.10.14 |
---|---|
object==module 또는 null==object? (0) | 2022.10.14 |
특정 문자 뒤에 문자열 부분 제거 (0) | 2022.10.14 |
Java에서의 Ctrl+C 캡처 (0) | 2022.10.14 |
사용자 입력 문자열을 정규식으로 변환하는 중 (0) | 2022.10.14 |