Use last inserted id as username - mysql

i would like that whenever i insert a row the newly generated id be used as a username and also get inserted in the user_name field. Any idea on how how i can achieve this will be much appretiated.
I have tried to run the below code on mysql workbench,and everything seem to work fine except for the insert statement.
create database if not exists mydatabase;
create table if not exists mydatabase.mytable
(
id int auto_increment not null,
user_name int not null,
pass_word varchar(100),
primary key(id)
);
insert into mydatabase.mytable(user_name,pass_word) values (select SCOPE_IDENTITY(),'mypass');

Not sure if your version of sql supports multiple auto_increment columns. However I'm thinking you could either create a trigger or insert the following every time you do an insert:
update my_table
set user_name = id

Related

MySql result won't update after new changes

So I made a change from 'Chemistry' to 'Physic' on 'major' column but as soon I executed it nothing changes and shows the same result. Why? (I used MySql Workbench)
Here's the original code:
CREATE TABLE people_data1 (
id INT,
username VARCHAR(20),
major VARCHAR(20) UNIQUE,
PRIMARY KEY(id)
);
# Insert some data into the table
INSERT INTO people_data1(id,username) VALUES(3,'Clara'); # Person with no major
INSERT INTO people_data1 VALUES(51,'Mr Bald','Chemistry'); # Change to 'Physic'
SELECT * FROM people_data1;
The new one:
CREATE TABLE people_data1 (
id INT,
username VARCHAR(20),
major VARCHAR(20) UNIQUE,
PRIMARY KEY(id)
);
# Insert some data into the table
INSERT INTO people_data1(id,username) VALUES(3,'Clara'); # Person with no major
INSERT INTO people_data1 VALUES(51,'Mr Bald','Physic');
SELECT * FROM people_data1;
Inserts add new records; you want an update here:
UPDATE people_data1
SET major = 'Physics'
WHERE id = 51;
Run this update after your first two insert statements to get your desired results.

How to set custom auto_increment value with initial value in MySQL [duplicate]

How do I set the initial value for an "id" column in a MySQL table that start from 1001?
I want to do an insert "INSERT INTO users (name, email) VALUES ('{$name}', '{$email}')";
Without specifying the initial value for the id column.
Use this:
ALTER TABLE users AUTO_INCREMENT=1001;
or if you haven't already added an id column, also add it
ALTER TABLE users ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT,
ADD INDEX (id);
MySQL - Setup an auto-incrementing primary key that starts at 1001:
Step 1, create your table:
create table penguins(
my_id int(16) auto_increment,
skipper varchar(4000),
PRIMARY KEY (my_id)
)
Step 2, set the start number for auto increment primary key:
ALTER TABLE penguins AUTO_INCREMENT=1001;
Step 3, insert some rows:
insert into penguins (skipper) values("We need more power!");
insert into penguins (skipper) values("Time to fire up");
insert into penguins (skipper) values("kowalski's nuclear reactor.");
Step 4, interpret the output:
select * from penguins
prints:
'1001', 'We need more power!'
'1002', 'Time to fire up'
'1003', 'kowalski\'s nuclear reactor'
MySQL Workbench
If you want to avoid writing sql, you can also do it in MySQL Workbench by right clicking on the table, choose "Alter Table ..." in the menu.
When the table structure view opens, go to tab "Options" (on the lower bottom of the view), and set "Auto Increment" field to the value of the next autoincrement number.
Don't forget to hit "Apply" when you are done with all changes.
PhpMyAdmin:
If you are using phpMyAdmin, you can click on the table in the lefthand navigation, go to the tab "Operations" and under Table Options change the AUTO_INCREMENT value and click OK.
With CREATE TABLE statement
CREATE TABLE my_table (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
) AUTO_INCREMENT = 100;
or with ALTER TABLE statement
ALTER TABLE my_table AUTO_INCREMENT = 200;
First you need to add column for auto increment
alter table users add column id int(5) NOT NULL AUTO_INCREMENT FIRST
This query for add column at first.
Now you have to reset auto increment initial value. So use this query
alter table users AUTO_INCREMENT=1001
Now your table started with 1001
You could also set it in the create table statement.
`CREATE TABLE(...) AUTO_INCREMENT=1000`
Alternatively, If you are too lazy to write the SQL query. Then this solution is for you.
Open phpMyAdmin
Select desired Table
Click on Operations tab
Set your desired initial Value for AUTO_INCREMENT
Done..!
For this you have to set AUTO_INCREMENT value
ALTER TABLE tablename AUTO_INCREMENT = <INITIAL_VALUE>
Example
ALTER TABLE tablename AUTO_INCREMENT = 101
Also , in PHPMyAdmin , you can select table from left side(list of tables) then do this by going there.
Operations Tab->Table Options->AUTO_INCREMENT.
Now, Set your values and then press Go under the Table Options Box.
SET GLOBAL auto_increment_offset=1;
SET GLOBAL auto_increment_increment=5;
auto_increment_increment: interval between successive column values
auto_increment_offset: determines the starting point for the AUTO_INCREMENT column value.
The default value is 1.
read more here

Auto_Increment not working on insert query

Need help how to solve this problem...
I have created a users table which has following columns
Create table users
(
uid int(10) PRIMARY KEY AUTO_INCREMENT,
uname varchar(50),
password varchar(50),
email varchar(50)
);
when i insert values with uid it executes successfully :
Insert into users values(1,'ABC','Helloworld','ABC#gmail.com');
but when i try without uid
Insert into users values('SDC','Helloworld','SDC#gmail.com');
it does not execute successfully and gives an error
ERROR 1136 (21S01): Column count doesn't match value count at row 1
my uid has AUTO_INCREMENT so it should automatically increase..
Of course auto_increment is working correctly. You just need to learn best practices about using insert. Always list all the columns (unless you really, really know what you are doing):
Insert into users (uname, password, email)
values('SDC', 'Helloworld', 'SDC#gmail.com');
The id column will be auto-incremented. If you don't list the columns, then MySQL expects values for all columns, including the auto-incremented one.

MySQL trigger delete passing user ID

I need to create MySQL trigger that would log user ID on delete table row statement which must fit in one query, since I'm using PHP PDO. This is what I've come up so far:
I need the way to pass user ID in the delete query even though it is irrelevant to delete action to be performed:
Normally the query would look like this:
DELETE FROM mytable WHERE mytable.RowID = :rowID
If I could use multiple queries in my statement, I would do it like this:
SET #userID := :userID;
DELETE FROM mytable WHERE mytable.RowID = :rowID;
This way the variable #userID would be set before trigger event fires and it can use it. However since I need to squeeze my delete statement in one query, so I came up with this:
DELETE FROM mytable
WHERE CASE
WHEN #userID := :userID
THEN mytable.RowID = :rowID
ELSE mytable.RowID IS NULL
END
Just a note: RowID will never be null since it's the primary key. Now I have to create a delete trigger to log the user ID to the audit table, however I suppose that in this case trigger will be fired before the delete query itself which means that #userID variable will not be created? This was my idea of passing it as a value to the trigger.
I feel like I'm close to the solution, but this issue is a blocker. How to pass user ID value to the trigger without having multiple queries in the statement? Any thoughts, suggestions?
You can use NEW / OLD mysql trigger extensions. Reference: http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html
Here is a sample code :
drop table `project`;
drop table `projectDEL`;
CREATE TABLE `project` (
`proj_id` int(11) NOT NULL AUTO_INCREMENT,
`proj_name` varchar(30) NOT NULL,
`Proj_Type` varchar(30) NOT NULL,
PRIMARY KEY (`proj_id`)
);
CREATE TABLE `projectDEL` (
`proj_id` int(11) NOT NULL AUTO_INCREMENT,
`proj_name` varchar(30) NOT NULL,
`Proj_Type` varchar(30) NOT NULL,
PRIMARY KEY (`proj_id`)
);
INSERT INTO `project` (`proj_id`, `proj_name`, `Proj_Type`) VALUES
(1, 'admin1', 'admin1'),
(2, 'admin2', 'admin2');
delimiter $
CREATE TRIGGER `uProjectDelete` BEFORE DELETE ON project
FOR EACH ROW BEGIN
INSERT INTO projectDEL SELECT * FROM project WHERE proj_id = OLD.proj_id;
END;$
delimiter ;
DELETE FROM project WHERE proj_id = 1;
SELECT * FROM project;
SELECT * FROM projectDEL;

knowing next value from auto increment field mysql java

I want to know the next value of auto increment field
I wanted to test this :
select max(contactid) from contact
and I add 1
but I realized that it can give me an error
for exemple
if I insert one record and I delete it
so if I insert after the field will increase by two
how can I achieve that ?
thank you
There are multiple solutions to this problem:
1. (Preferable) Stop trying to predict auto-increment values
This is the more typical case, and basically is using auto-increment as designed. This assumes that you don't actually need the auto-increment value before you insert. What you can do is:
DROP TABLE IF EXISTS t;
CREATE TABLE t (id INT UNSIGNED NOT NULL auto_increment, x INT NOT NULL, PRIMARY KEY(id));
INSERT INTO t (x) VALUES (100);
SELECT LAST_INSERT_ID();
The call to SELECT LAST_INSERT_ID() will return the ID that was just generated for your INSERT.
2. Set up an ID generation table specifically to generate IDs
You can create a table with just an auto-increment column, like so:
DROP TABLE IF EXISTS id_generator;
CREATE TABLE id_generator (id INT UNSIGNED NOT NULL auto_increment, PRIMARY KEY(id));
You can then generate a new, unique ID with:
INSERT INTO id_generator (id) VALUES (NULL);
SELECT LAST_INSERT_ID();
And use that ID to insert into the table you're actually working with. As long as all generated IDs come from this ID generation table, there will be no conflicts. However there is a cost to generating these IDs, and auto-increment is not very efficient at it.
3. Use an external ID generation scheme
This is more or less similar to solution 2, but doesn't use MySQL at all for the ID generation. You can use something like a UUID/GUID scheme which generates a string, or you could use something like Snowflake to generate integer IDs.
You should use LAST_INSERT_ID like this:
SELECT LAST_INSERT_ID()
It will return the last value of AUTO_INCREMENT ID field.
More details here: http://goo.gl/RkmR5
This will give you the next id value that will be inserted:
SELECT LAST_INSERT_ID() + 1;