2016-12-05 185 views
4

我有一個連接表叫carriers_rects,看起來像這樣:mysql UPDATE說列不能爲空。爲什麼它是空的?

+------------+------------------+------+-----+---------+----------------+ 
| Field  | Type    | Null | Key | Default | Extra   | 
+------------+------------------+------+-----+---------+----------------+ 
| id   | int(11) unsigned | NO | PRI | NULL | auto_increment | 
| carrier_id | int(11) unsigned | NO |  | NULL |    | 
| rect_id | int(11) unsigned | NO |  | NULL |    | 
+------------+------------------+------+-----+---------+----------------+ 

我也有一個rects表看起來像這樣:

+---------+-------------+------+-----+----------+----------------+ 
| Field | Type  | Null | Key | Default | Extra   | 
+---------+-------------+------+-----+----------+----------------+ 
| id  | int(11)  | NO | PRI | NULL  | auto_increment | 
| name | varchar(54) | NO |  | new rect |    | 
| width | varchar(54) | NO |  | NULL  |    | 
| length | varchar(54) | NO |  | NULL  |    | 
| rounded | tinyint(1) | NO |  | NULL  |    | 
| xx  | varchar(54) | NO |  | NULL  |    | 
| yy  | varchar(54) | NO |  | NULL  |    | 
| height | varchar(54) | NO |  | NULL  |    | 
+---------+-------------+------+-----+----------+----------------+ 

我想一個case_id列添加到rects和只是使其成爲one-to-many關係並殺死carriers_rects表。我們正在移動我們的數據庫,我們從未使用過many-to-many關係。

所以我加入了case_idrects

alter table rects add case_id int(11) not null; 

然後我嘗試了所有case_id的,將匹配來自carriers_rects表以更新rects的case_id

update rects set case_id = (select carrier_id from carriers_rects where rect_id = id); 

我得到column case_id cannot be null

我測試過,看看有沒有空位,我似乎找不到任何。

select * from (select * from carriers_rects where rect_id IN(select id from rects)) `b` where id is null; 

我也嘗試了另一種方式,因爲老實說我有點困惑。

select id from rects where id IN(select rect_id from carriers_rects) 

顯然我不是sql天才。但是很想在這裏接受教育。 不知道爲什麼我得到上面提到的錯誤。

回答

2

此錯誤的主要原因是在你的內心查詢條件rect_id = id。他們都從carriers_rects(這意味着carriers_rects.rect_id = carriers_rects.id),所以你得到null。將其更改爲rect_id = rects.id

update rects set case_id = 
(select carrier_id from carriers_rects where rect_id = rects.id); 
+0

我在嘗試時仍然遇到同樣的錯誤。儘管這聽起來很不錯, – Johnston

+0

@Johnston這意味着你有'rects.id'不存在於'carriers_rects'表中。你可以使用@Rahul的JOIN語法,或者將條件添加到這個UPDATE中:'WHERE EXISTS(從carrier_rects中選擇carrier_id,其中rect_id = rects.id)' – valex

+0

下面我的查詢不會測試嗎?這就是我的想法,所以我寫了這些查詢來測試它,它聽起來並不像它有任何問題。 – Johnston

2

如果你更改爲update-join語法,而不是使用子查詢像

update rects r 
join carriers_rects cr on cr.rect_id = r.id 
set r.case_id = cr.carrier_id 
where cr.carrier_id is not null; 
+0

這是行不通的!我仍然不明白我爲什麼不工作。但我很高興有一些工作。 – Johnston