简体   繁体   English

SQL 插入值列,其中值来自另一列

[英]SQL Insert values column where values is from another column

在此处输入图片说明

I have a table like this in MySQL, and I want to add values into the kodeunik column where the value is a combination of Kode , Daerah and NomorKode我在 MySQL 中有一个这样的表,我想将值添加到kodeunik列中,其中该值是KodeDaerahNomorKode的组合

Expected output for kodeunik column: kodeunik列的预期输出:

Bank BCA       101    00   0003   101000003

Bank BCA PT    101    00   0003   101000001

Bank BNI       101    00   0003   101000004

Question:题:

  1. How to query like that?这样查询怎么办?

  2. Is it possible to make the kodeunik as primary key?是否可以将kodeunik作为主键?

There is no need to do this;没有必要这样做; you can simply generate the value on the fly:您可以简单地动态生成值:

SELECT *, CONCAT(Kode, Daerah, NomorKode) AS kodeunik
FROM yourTable

or create a VIEW :或创建一个VIEW

CREATE VIEW yT_ke AS
    SELECT *, CONCAT(Kode, Daerah, NomorKode) AS kodeunik
    FROM yourTable;
SELECT * FROM yT_ke

Output (for both queries):输出(对于两个查询):

JenisPerkiraan  Kode    Daerah  NomorKode   kodeunik
Bank BCA        101     00      0003        101000003
Bank BCA PT     101     00      0001        101000001
Bank BNI        101     00      0004        101000004

If you want a primary key on this combined field, just add it over the 3 columns:如果你想要这个组合字段的主键,只需将它添加到 3 列上:

 ALTER TABLE yourTable ADD PRIMARY KEY (Kode, Daerah, NomorKode)

Demo on dbfiddle dbfiddle 上的演示

  1. You can use Update query to achieve it.您可以使用Update查询来实现它。
    UPDATE your_table_name
    SET kodeunik = concat(`Kode`, `Daerah`, 'NomorKode`)
  1. If you make sure kodeunik value is unique, you can also make it as primary key.如果您确保kodeunik值是唯一的,您还可以将其设为主键。

Mysql has CONCAT() function. Mysql 有CONCAT()函数。 In your case, you can try:在您的情况下,您可以尝试:

select CONCAT(Kode, Daerah, NomorKode) from <your_table_name>;

If it is what you want, you can use subquery to update them.如果这是您想要的,您可以使用子查询来更新它们。

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

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