简体   繁体   English

如何将空值传递给外键字段?

[英]how to pass a null value to a foreign key field?

I have 2 tables: 我有2张桌子:

university : university

university_id(p.k) | university_name

and user : user

uid | name | university_id(f.k)

How to keep university_id NULL in user table? 如何在用户表中保持university_id

I am writting only 1 query, my query is: 我只写了1个查询,我的查询是:

INSERT INTO user (name, university_id) VALUES ($name, $university_id);

Here $university_id can be null from front end. 这里$university_id从前端可以为null。

university table will be set bydefault by me. university表将由我设置为默认。

In the front end, student will select the university name, according to that the university_id will pass to user table, but if student is not selecting any university name then is should pass null value to the user table for university_id field. 在前端,学生将选择大学名称,根据university_id将传递给user表,但如果学生没有选择任何大学名称,则应将null值传递给university_id字段的user表。

Just allow column university_id of table user to allow NULL value so you can save nulls . 只要允许列university_id表的user ,允许NULL值,这样可以节省

CREATE TABLE user
(
   uid INT NOT NULL,
   Name VARCHAR(30) NOT NULL, 
   university_ID INT NULL,    -- <<== this will allow field to accept NULL
   CONSTRAINT user_fk FOREIGN KEY (university_ID)
       REFERENCES university(university_ID)
)

UPDATE 1 更新1

based on your comment, you should be inserting NULL and not '' . 根据你的评论,你应该插入NULL而不是''

insert into user (name,university_id) values ('harjeet', NULL)

UPDATE 2 更新2

$university_id = !empty($university_id) ? "'$university_id'" : "NULL";
insert into user (name,university_id) values ('harjeet', $university_id);

As a sidenote, the query is vulnerable with SQL Injection if the value( s ) of the variables came from the outside. 作为一个旁注,查询是脆弱的SQL Injection ,如果变量的值(一个或多个 )从外面走了进来。 Please take a look at the article below to learn how to prevent from it. 请查看下面的文章,了解如何防止它。 By using PreparedStatements you can get rid of using single quotes around values. 通过使用PreparedStatements您可以摆脱使用值周围的单引号。

Here suppose i have foreign key user_id and i want to insert null value for that. 这里假设我有外键user_id ,我想为此插入空值。

在此输入图像描述

Checkbox must be checked for insert null value for foreign key. 必须检查复选框是否为外键插入空值。

I was using MySQL InnoDB and even allowing NULL in the FK column and using NULL as default I was getting an error. 我使用MySQL InnoDB,甚至在FK列中允许NULL并使用NULL作为默认值我遇到了错误。 So I used the SET syntax: 所以我使用了SET语法:

INSERT INTO (table) SET value1=X...

And I just don't set the FK column. 我只是不设置FK列。

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

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