SQL column name based on primary key [duplicate] - mysql

This question already has answers here:
How to make MySQL table primary key auto increment with some prefix
(4 answers)
Autoincrement ID with a prefix
(3 answers)
Closed 5 years ago.
ID column set to primary key, auto increment.
I want to have a second column Project number, is it possible to set something like this in SQL ? Or how should I do this ?
ID: 1 projectnumber:Project001
ID: 2 projectnumber:Project002
.
.
.
ID: n projectnumber: Project00n

you could do that in 2 ways:
Either using a trigger or do that when retrieving the record from the database:
trigger: after insert
CREATE TRIGGER `yourtable_after_insert` AFTER INSERT ON `yourtable` FOR EACH ROW BEGIN
UPDATE yourtable
SET projectnumber = CONCAT('project', NEW.id)
WHERE id = NEW.id;
END;
or
just do that CONCAT thing in your select query or even better in the logic of php. Consider the possibility you want to translate your application. You would store duplicate information as well...
as pointed out below: NEW.id will not work.
So use LAST_INSERT_ID() instead:
CREATE TRIGGER `yourtable_after_insert` AFTER INSERT ON `yourtable`
FOR EACH ROW BEGIN
UPDATE yourtable
SET projectnumber = CONCAT('project', LAST_INSERT_ID())
WHERE id = LAST_INSERT_ID();
END;
but still: it would be duplicating content

Related

insert many rows, LAST_INSERT_ID return 1 [duplicate]

This question already has answers here:
MySQL LAST_INSERT_ID() used with multiple records INSERT statement
(3 answers)
Closed 3 years ago.
Have:
1. create DB
2. create Table
3. insert 3 rows
4. select LAST_INSERT_ID()
Here test code:
DROP DATABASE IF EXISTS TEST;
CREATE DATABASE TEST;
USE TEST;
CREATE TABLE test (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
age INT
);
INSERT INTO test (age) VALUES (1), (2), (3);
SELECT LAST_INSERT_ID();
Why LAST_INSERT_ID() return 1 ?
Excepted: 3
How to get valid LAST_INSERT_ID() ?
The MySQL documentation clearly explains this behavior:
With no argument, LAST_INSERT_ID() returns a BIGINT UNSIGNED (64-bit) value representing the first (emphasis mine) automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement. The value of LAST_INSERT_ID() remains unchanged if no rows are successfully inserted.
The first value generated by the auto increment sequence in the insert was 1, not 2 or 3, so the value 1 gets returned.
I think the confusion you have is around the name LAST_INSERT_ID. The "last" part refers to the most recent insert statement, not the most recent id value within that insert.

Delete row before insert a new one [duplicate]

This question already has an answer here:
INSERT deleted values into a table before DELETE with a DELETE TRIGGER
(1 answer)
Closed 6 years ago.
How can I achieve to Delete a row before Insert a new one in the same Table. I tried it with a Trigger but I read that it is not possible because it could cause a deadlock.
I also wanted to save the row which should be deleted to another table (example Table B) before delete it and then Insert a new one (into Table A).
Is there any other ways to do it ?
PS: They will have the same key
You could use UPDATE...
UPDATE tbl
SET col1 = newCol1,
col2 = newCol2
WHERE etc = etc
And If you want to insert updated row to another table you could use TRIGGER AFTER UPDATE for that.
CREATE TRIGGER TriggerName ON Tbl
AFTER UPDATE
AS
INSERT INTO Log (Col1, Col2)
SELECT Col1, Col2
FROM deleted

How to use replace to non unique keys? mysql [duplicate]

This question already has answers here:
Insert into a MySQL table or update if exists
(12 answers)
Closed 8 years ago.
I have this table:
rating | businessId | userId
============================
1 200 1
2.5 200 2
the user can't has two rows with the same businessId,
for example:
rating | businessId | userId
============================
1 200 1
2.5 200 1
this's incorrect;
my server receive the businessId,userId and rating.
then it should update the row which has the same userId, and businessId if exist, else create new row.
How could I implement that with one query ?
It is possible to perform a single query which will either insert or update a row, by using MySQL procedures. However, it's very likely to be better to test whether the row exists first in your chosen language, and then either insert or update as appropriate. This will allow you to give appropriate feedback to the user, and other things which depend on whether the row existed before.
Suppose you get these three values #rating ,#userId,#businessId then you would write you UPSERT (UPDATE/Insert) query something like this.....
IF EXISTS (SELECT 1 FROM dbo.TableName
WHERE userId = #userId AND businessId = #businessId)
BEGIN
UPDATE dbo.TableName
SET businessId = #businessId
,rating = #rating
WHERE userId = #userId
END
ELSE
BEGIN
INSERT INTO dbo.TableName (userId, businessId, rating)
VALUES (#userId, #businessId, #rating)
END

MySQL: SELECT and UPDATE in one statement [duplicate]

This question already has answers here:
With MySQL, how can I generate a column containing the record index in a table?
(8 answers)
Closed 8 years ago.
I have: Select some set of pairs. The first column is the id of row in table, the second is the new value which should be assigned to that row.
-- the first query
CREATE TABLE tmp;
SELECT row_id, new_value
FROM [not essential tables and joins]; //PSEUDOCODE
-- another queries
FOR EACH tmp //PSEUDOCODE
UPDATE table SET value = new_value WHERE id = row_id;
-- QUESTION: CAN I MERGE SELECT AND UPDATE IN ONE QUERY?
-- I want avoid creating temporary table.
Problem: Iteration through table (as in example above) decrease clearness and speed of code.
Question: *How to do the same in single query
I think you are looking for update the table join with other table (Not sure though). You can do something like
UPDATE tmp a
JOIN sometable b ON a.col = b.col
AND a.id = b.row_id
SET a.value = b.new_value

Find next value of AUTO_INCREMENT column in MySQL [duplicate]

This question already has answers here:
How to get the next auto-increment id in mysql
(21 answers)
Closed 9 years ago.
I am using MySQL.
I want to retrieve the next value that the AUTO_INCREMENT column will take without entering a new record.
create table ABC(id int(10) NOT NULL AUTO_INCREMENT,name char(10));
In oracle I would have used sequencename.nextval(); But what to I use in MySQL?
Here is why I did not use
select max(id) from ABC;
Suppose I have an entry with id=2. Now column id will take the next value as 3.
Before I create a record with id=3, If I delete the record with id=2.
The answer for query I mentioned will be 2. But I want the actual value 3, which the auto_increment column will anyway take.
Query table status like this:
SHOW TABLE STATUS WHERE `Name` = 'table_name'
Now in result you will get a column named Auto_increment. This is the value You were asking for.
In JAVA:
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
rs = stmt.executeQuery("SHOW TABLE STATUS WHERE `Name` = 'table_name'");
rs.next();
String nextid = rs.getString("Auto_increment");
Full example here: http://www.avajava.com/tutorials/lessons/how-do-i-use-jdbc-to-query-a-mysql-database.html
If I understand correctly,you could use the number of rows as indicator:
SELECT TABLE_ROWS+1
FROM information_schema.tables
WHERE table_name='tableName'
AND table_schema = DATABASE();
There is no way to guarantee what value you are going to get before inserting the row. This is mostly because you will have to lock the entire table to guarantee no other thread will do an insert with "your" next value.
You can reserve a value by starting a transaction, inserting a row, getting the value and then doing a rollback. Then you can safely use that value.
It will be much simpler to just insert the row, so maybe I'm not understanding the purpose of what you are doing.