Auto Increment in sql with specific name - mysql

i need autoincrement. for start like abc_1,abc_2. like this format? below shown code is for auto increment. but i need format like abc_ is constatanct then auto increment, format like abc_1,abc_2..
CODE
sql = "CREATE TABLE MY_TABLE
(
table_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(table_id),
table_1 varchar(45),
table_2 varchar(45),
table_3 varchar(999),
table_4 varchar(45)
)"

You have 2 options - both include keeping the autoincrement field exactly as it is.
1st Option is to add a short char type field, which simply stores your Alpha part. When you want to retrieve the whole key, then you can SELECT (alpha_part + table_id) as ID. As you can see this generates smaller storage, but requires more work for each select statement.
2nd option is to add a longer column that gets populated by an insert trigger normally. It is simply storing the concatenation on creation and then you don't have to concatenate it when you want to select it. This option also allows you to create an index or clustered index easier.
CREATE TABLE MY_TABLE (
table_id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(table_id),
alpha_part varchar(10) NOT NULL, -- This
display_id varchar(40) NOT NULL, -- OR This (not both)
table_1 varchar(45),
table_2 varchar(45),
table_3 varchar(999),
table_4 varchar(45) )
"Database Id" and "Insurance Policy Id" are two separate entities - they may contain the "same" number, but don't mix up what the database needs to perform effectively, with what your business application needs to generate IDs for customers. Business rules and database Id are separate entities. You can "seed" a policy Id from a database generated one, but if something changes the policy id (yes this happens) your database suddenly needs to be refactored and you don't want that to happen.

You could add another column to derive this value, then have a trigger that automatically updates this column to add the derived value whenever a row is inserted.
However, it is not clear why this would be needed. It is likely better to just store the number and derive the form abc_123 where that value needs to be used.

It was an interesting thing. so I googled custom auto increment structure and found some links. Most of the people are saying that its better to use trigger before insertion and I think it can be on possible solution for your problem. Look at the following link.
http://www.experts-exchange.com/Database/MySQL/Q_27602627.html

Related

Can columns be linked in MySql?

Is there a way to link two fields in a table so that one auto-increments, but resets to zero when the other field changes? For example, I have the following table in MySQL:
CREATE TABLE searches(
searchID INT UNSIGNED NOT NUL,
userID INT UNSIGNED NOT NULL,
searchParams VARCHAR(100) DEFAULT NULL,
creationDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX(userID, searchID)
)ENGINE MyISAM;
The same user can create several searches, so what I want is to have searchID start at 1 whenever a new userID is entered, and increment automatically if a record to be inserted has a userID for which there are previous entries already. Can this be achieved somehow at table definition time? If not, can it be achieved with a single insert statement? Thanks in advance.
Is there a way to link two fields in a table so that one
auto-increments, but resets to zero when the other field changes?
NO, there is none; unless you build a trigger and make this change happen. Though I don't see how this would be helpful considering that one is a AUTO_INCREMENT column. You will unnecessary reseed it again and again.

2 independent auto_incremental fields in MySQL table

I am trying to create a MySQL table that has a generic ID column, but also a secondary ID column, both of which need some form of auto incrementing
currently my MySQL table looks like this:
`ban_id` mediumint unsigned NOT NULL AUTO_INCREMENT,
`student_uuid` varchar(36) NOT NULL,
`student_ban_id` tinyint unsigned NOT NULL AUTO_INCREMENT,
(a bunch of data irrelevant to this question)
PRIMARY KEY (`student_uuid`, `student_ban_id`),
UNIQUE (`ban_id`)
The desired behavior is that ban_id is just a generic entry_id and that student_ban_id is the ban's number for the given student. (my reasoning is that I want to be able to reference bans by an id value if the student_uuid is unavailable, but the program spec also requires the ability to take student:banID as a valid means of reference)
A example row might be BanID:501, {studentUUID}, studentBanID:2 (501st ban, 2nd ban against the given student)
I have run into the issue that the MyISAM engine does not support tracking two separate incremental columns at once (I believe it can handle both desired behaviors, but not at the same time)
What might be the best way to achieve such a behavior?
Much appreciated!
-Cryptic

Concatenating a str to an auto incrementeed column which functions as primary key

Having some trouble putting together a table with a unique value. The current setup I have for two tables which for all intents and purposes can be the same as the one below. My problem is that I'm trying to use the auto incremented value as the primary key due to redundancies in the data pulls, but since it's for two tables, I want to concatenate a string to the auto incremented value so my ID column would be:
Boop1, Boop2, Boop3 and Beep1, Beep2, Beep3, instead of 1, 2, 3 for both tables so they are differentiated and thus do not have duplicate values when I put in constraints
CREATE TABLE IF NOT EXISTS `beep`.`boop` (
`ID` INT NOT NULL AUTO_INCREMENT,
`a` VARCHAR(15) NOT NULL,
`b` VARCHAR(255) NOT NULL,
`c` VARCHAR(50) NOT NULL,
`d` VARCHAR(50) NOT NULL,
PRIMARY KEY(`ID`))
ENGINE = InnoDB;
LOAD DATA LOCAL INFILE 'blah.csv'
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES SET DCMID = CONCAT('DCM'+`DCMID`);
The code in boldface is optional and was only there to try concatenating which I already know does not work
I realize that this would not be able to work since my datatype is an INT, so what would I have to do to to keep my autoincrement while differentiating
For reference, I am using a LOAD DATA LOCAL INFILE, and not INSERT (and I don't think bulk insert is available with mySQL workbench). otherwise, i would bulk insert and just utilize last_insert_id
The goal is to plug and play for a datapull I perform so I can archive my data quickly and run queries to grab the data I need in the future. using one insert line per row of data i have would be extremely inefficient
I was utilizing a delimiter function earlier with a trigger, which in theory would have worked by altering the table after the load data infile, but that requires SUPER privileges which I do not have
is what i'm asking for even possible, or should i give up and find a workaround, or try grabbing super priveleges and trying the delimiter trigger
I'm not sure why you would do that, but you could use two different indexes. The first one is the auto-increment, and is populated by MySQL. The second one is your "prefixed" key, and is created by a trigger called after insert, where you update the column based on the first key and the prefix that you want.

MySQL duplication

Using SQLyog, I was testing whether the correct value was set into table.
And I tried
SELECT type_service FROM service WHERE email='test#gmail.com'
So, only one result was output.
type_service
0
To continue to test, I tried to set value, 1 by force which gave the warning
Warning
There are 2 duplicates of the row you are trying to update. Do you
want to update all the duplicates?
Note: You can turn off this warning by unchecking Tools -> Preferences -> Others -> Prompt if multiple rows are getting updated.
But I thought I already placed limitations with where clause. So I pushed yes.
As a result, the value of all the data in type_service column was changed to 1.
Why?
You have 2 exact duplicate rows in table. Exact. It is a friendly warning, but most likely needs to be addressed by a slight schema change.
The most simple solution is to alter the table and add an auto_increment Primary Key column.
Mysql Alter Table Manual page here.
See this Webyog FAQ link.
Whenever I am about to spook up another table, I usually stub it out like:
create table blah
(
id int auto_increment primary key,
...
...
...
);
for safety sake.
Were you not to have the auto_increment PK, see the following.
create table people
(
firstName varchar(40) not null,
lastName varchar(40) not null,
age int not null
);
insert people (firstName,lastName,age) values ('Kim','Billings',30),('Kim','Billings',30),('Kim','Billings',30);
select * from people;
-- this could be bad:
update people
set age=40
where firstName='Kim' and lastName='Billings';
ALTER TABLE people ADD id INT PRIMARY KEY AUTO_INCREMENT;
select * from people; -- much nicer now, schema has an id column starting at 1
-- you now at least have a way to uniquely identify a row

Table issue in SQL Server 2008

I have a table in SQL Server 2008 like this:
Column DataType
-----------------------
FID numeric(18, 0)
Name varchar(50)
DOB datetime
MobileNo numeric(18, 0)
EmailId varchar(50)
add1 varchar(50)
add2 varchar(50)
add3 varchar(50)
Pincode numeric(18, 0)
UpdateDate datetime
In this table FID should be changed to varchar(50) without dropping (deleting) the table..
How to do this and also FID is set as primary key to the above table and also as a foreign key to other tables
As I said - I would leave the column FID as it is - otherwise, you'll have a ripple effect throughout your entire data model, and this is really really not what you want to do.
What you can do is this: create a new, separate column that contains that new prefix that the "hgiher ups" are so desperate for, and concatenates this with the FID value - but it's a separate column, and you don't need to change any of the references at all.
ALTER TABLE dbo.YourTable
ADD FID2 AS 'MU' + CAST(FID AS VARCHAR(20)) PERSISTED
With this, you'll get a VARCHAR typed new column called FID2 which will have values like MU1, MU2 ..... and so on - automatically, no changes necessary, no messy table re-creations and data copying.... it just works!
Tools->Options->designers->(Unmark)Prevent saving changes that require table recreation
Right click table -> Design -> Change the numeric(18, 0) to varchar(50) -> Save
It will ask for confirmation since changing from one data type to another removes certain precision values.
The best practice is to keep Primary and foriegn keys unique numbers. But you may opt for unique code values too which are varchar values
And one more thing, changing the primary key field datatype automatically changes the datatype of all relational foreign key fields in other tables too.