2017-05-08 65 views
0

表架構:如何將某些行的列值設置爲與同一表中的其他行相同?

+----------------------+---------------+------+-----+---------+-------+ 
| Field    | Type   | Null | Key | Default | Extra | 
+----------------------+---------------+------+-----+---------+-------+ 
| name     | varchar(10) | YES | MUL | NULL |  | 
| slno     | varchar(20) | YES |  | NULL |  | 
| type     | int(2)  | YES |  | NULL |  | 
| details    | text   | YES |  | NULL |  | 
+----------------------+---------------+------+-----+---------+-------+ 

名稱,slno並鍵入一起形成鍵。

的樣本數據:

+---------+------+------+-------------------------------+ 
| name | slno | type | details      | 
+---------+------+------+-------------------------------+ 
| name1 | 11 | 1 | {"data":["feats1","feats2"] } | 
| name1 | 11 | 2 | {"data":["feats1","feats2"] } | 
| name1 | 12 | 1 | {"data":["feats5","feats6"] } | 
| name1 | 12 | 2 | {"data":["feats5","feats6"] } | 
| name2 | 11 | 1 | {"data":["feats3","feats4"] } | 
| name2 | 11 | 2 | {"data":["feats3","feats4"] } | 
| name2 | 12 | 1 | {"data":["feats7","feats8"] } | 
| name2 | 12 | 2 | {"data":["feats10"] }   | 
+---------+------+------+-------------------------------+ 

所以基本上與NAME = '名稱1' 中的每個條目,有一個與同slno但名稱= '名2' 類似的條目。
我想要做的是對具有相同slno和類型但名稱不同的行設置相同的細節,即上面的示例數據集應該如下所示。 name2行'的細節應該匹配name1行的細節,如果他們有相同的slno和類型。

+---------+------+------+-------------------------------+ 
| name | slno | type | details      | 
+---------+------+------+-------------------------------+ 
| name1 | 11 | 1 | {"data":["feats1","feats2"] } | 
| name1 | 11 | 2 | {"data":["feats1","feats2"] } | 
| name1 | 12 | 1 | {"data":["feats5","feats6"] } | 
| name1 | 12 | 2 | {"data":["feats5","feats6"] } | 
| name2 | 11 | 1 | {"data":["feats1","feats2"] } | 
| name2 | 11 | 2 | {"data":["feats1","feats2"] } | 
| name2 | 12 | 1 | {"data":["feats5","feats6"] } | 
| name2 | 12 | 2 | {"data":["feats5","feats6"] } | 
+---------+------+------+-------------------------------+ 

我試過了,但是不能拿出執行上述結果的命令。有人可以幫忙嗎?

+0

所以slno和細節應該形成一個單獨的表? – Strawberry

+0

不,我給出了樣本數據(第二個表格)以及它應該如何轉換到下面(最後一個表格) – user3248186

+0

您如何選擇給定'slno/type'對的參考值?我的意思是,你爲什麼選擇'name1'的值而不是'name2'的值? –

回答

0

如果要求給NAME2詳細介紹了值從NAME1的詳細信息,你可以做到這一點在MySQL與join基於更新

update yourTable as t1 
join yourTable as t2 
on  t1.slno = t2.slno and 
     t1.type = t2.type 
set  t2.details = t1.details 
where t2.name = 'name2' and 
     t1.name = 'name1' 

可以達到同樣也朝着我放在where條件子句的join條件

update yourTable as t1 
join yourTable as t2 
on  t1.slno = t2.slno and 
     t1.type = t2.type and 
     t2.name = 'name2' and 
     t1.name = 'name1' 
set  t2.details = t1.details 

你可以看到在行動這兩個查詢here

相關問題