Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql add "prefix" to every value in column

I need to add a 'prefix' in front of every value in a certain column.

Example: all fields in column x are: 200, 201, 202, 203, etc. I need them to be pn_200, pn_201, pn_202, pn_203, etc.

Is there a way to use ALTER or MODIFY commands to do this?

I would like something like ADD to BEGINNING of * column_name 'pn_'

Or perhaps a way to do it in PHP? Maybe get the value of the field, turn that into a variable, and do something like.

`$variablex = `'SELECT column_name FROM table'
$result = mysqli_query($con, variablex);
 foreach($r=mysqli_fetch_row($result) {
    `ADD TO BEGINNING OF * column_name 'pn_'`

Is there anyway to do that?

like image 543
Ghost Echo Avatar asked Oct 16 '13 20:10

Ghost Echo


People also ask

How do I add a prefix to a column in MySQL?

Learn MySQL from scratch for Data Science and AnalyticsCREATE OR REPLACE VIEW yourViewName AS SELECT *FROM yourTableName; To understand the above syntax, let us create a table. Insert some records in the table using insert command. Display all records from the table using select statement.

How to make indexing in MySQL?

To create indexes, use the CREATE INDEX command: CREATE INDEX index_name ON table_name (column_name); You can an index on multiple columns.

What is prefix in MySQL?

Introduction to MySQL Prefix IndexMySQL allows you to optionally create column prefix key parts for CHAR , VARCHAR , BINARY , and VARBINARY columns. If you create indexes for BLOB and TEXT columns, you must specify the column prefix key parts.

What is prefix in SQL?

Prefix enables developers to easily see what their code is doing as they write and test their code. Including SQL queries, HTTP calls, errors, logs, and much more. This makes Prefix really handy for viewing SQL queries your code is using. Prefix is free!


2 Answers

Actually it's even easier.

UPDATE table SET column_name = CONCAT('pn_', column_name)

Without a WHERE clause it will update all the rows of your table

like image 192
Machavity Avatar answered Sep 25 '22 08:09

Machavity


SELECT concat('pn_', column_name) AS column_name
FROM yourtable

but why do this at the database layer? It's trivial to do it in PHP:

SELECT column_name ...

while($row = mysql_fetch_assoc($result)) {
   $data = 'pn_' . $row['column_name'];
}
like image 26
Marc B Avatar answered Sep 24 '22 08:09

Marc B