简体   繁体   English

用同一行的值更新表

[英]Update a table with the value of the same row

I have a table like this 我有这样的桌子

id     Name   Parent_id   Text
1        x      0         
2        y      1         
3        Z      1        
4        A      2         
5        B      0         

Now i'd like to populate the column with the text of the column name depending on parent_id. 现在,我想根据parent_id用列名的文本填充列。 If parent_id is 0 text value will be the name of the same row instead id parent_id!=0 it must find the right name 如果parent_id为0,则文本值将是同一行的名称,而不是id parent_id!= 0,它必须找到正确的名称

this is the output I'd like to archieve 这是我想存档的输出

id     Name   Parent_id   Text
1        x      0         x
2        y      1         x
3        z      1         x
4        a      2         y
5        b      0         b

Could someone help me? 有人可以帮我吗?

First, write a SELECT statement that returns the row, along with the value you want to assign. 首先,编写一个SELECT语句返回该行以及要分配的值。 Something like this: 像这样:

SELECT t.id                            AS t_id
     , t.parent_id                     AS t_parent_id
     , t.name                          AS t_name
     , p.id                            AS p_id
     , p.name                          AS p_name
     , t.text                          AS t_text_old
     , IF(t.parent_id=0,t.name,p.name) AS t_text_new
  FROM tlt t
  LEFT
  JOIN tlt p
    ON p.id = t.parent_id

Not all of the columns in the SELECT list are necessary, but I find it helpful to examine the results to confirm that the statement is correct. 并不是SELECT列表中的所有列都是必需的,但是我发现检查结果以确认该语句正确是有帮助的。

Once you get the SELECT statement working, returning the new value(s) you want to assign to the column(s), convert that into an UPDATE statement. 一旦SELECT语句生效,将要分配给列的新值返回,将其转换为UPDATE语句。

Replace the SELECT ... FROM with the keyword UPDATE , and add a SET clause immediatly before the WHERE clause (or at the end of the statement if there isn't a WHERE clause. SELECT ... FROM替换为关键字UPDATE ,并立即在WHERE子句之前(如果没有WHERE子句,则在语句的末尾)添加SET子句。

UPDATE tlt t
  LEFT
  JOIN tlt p
    ON p.id = t.parent_id
   SET t.text = IF(t.parent_id=0,t.name,p.name)

Try: 尝试:

UPDATE tablename t
SET Text = 
      CASE 
           WHEN t.Parent_id = 0 THEN t.Name
           ELSE ( SELECT t1.name FROM tablename t1
                  WHERE t1.id = t.parent_id )
      END;

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

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