How to set primary key with auto increment in MYSQL - mysql

CREATE TABLE `journal` (
`yearr` int(4) NOT NULL,
`monthh` char(3) NOT NULL,
`volume` int(4) NOT NULL,
`issue` int(4) NOT NULL,
`pagefromto` varchar(10) NOT NULL,
`pissn` varchar(20) NOT NULL,
`eissn` varchar(20) DEFAULT NULL,
`name` varchar(50) NOT NULL,
`author1` varchar(10) DEFAULT NULL,
`author2` varchar(10) DEFAULT NULL,
`doc` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
)
ALTER TABLE `journal`
ADD PRIMARY KEY (`yearr`,`volume`,`issue`,`pagefromto`,`pissn`);
I need to add another key with auto increment to the above table structure

Your question is a bit confusing. You say you want to add a second primary key which will be auto increment... This doesn't make sense. They are called PRIMARY keys for a reason. There is only one primary key on a table as it is the, well, Primary key.
What I think you want to do is have a auto increment ID to use as the PK, which you could include in your create table like Arshad answered.
At that point, what you want to do is use your auto increment ID as the primary key (the same way you did with your PK, but put only the new ID in the PK, not the rest of your fields.), and you will want to use a unique index to make sure the combination of (yearr,volume,issue,pagefromto,pissn) doesn't repeat.
See this document to get more info on index creation
Note that if your table is already created, you'll have to delete the old primary key before you can add it on the ID.

You can use this query. This will create table with "id" as AutoIncrement and primary key
CREATE TABLE
tbl_employee (
id int(11) NOT NULL AUTO_INCREMENT,
employee_id int(4) NOT NULL,
employee_no int(6) NOT NULL,
employee_name varchar(60) NOT NULL,
department_id int(4) NOT NULL,
designation_id int(4) NOT NULL,
hired_date date NOT NULL,
salary int(10) NOT NULL,
PRIMARY KEY(id)
)

Related

How to make mysql table column as KEY, when already another column is set as PRIMARY KEY

In our mysql database, one table say "mytable" is having coumn mobile_no as primary key. But we are in need to make another column also as key. So that I can use that column in where condition.
Show create of table is below-:
CREATE TABLE `report_data` (
`api_request_id` int(11) NOT NULL AUTO_INCREMENT,
`emailid` varchar(100) NOT NULL,
`api_recipient_data` longtext,
`request_params` varchar(255) DEFAULT NULL,
`sent_date` date DEFAULT NULL,
`sent_time` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '1-processed, 2-success, 3-in-bounce, 4-invalid-domain,5-in-unsubscribe, 6-in-scrubbing',
`api_userid` int(11) DEFAULT NULL,
`domain_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`api_request_id`,`emailid`),
KEY `sent_date` (`sent_date`)
);
I want to add one new column to this existing table and make that column as KEY.
we want to add one column d_name and want it to make it as KEY
ALTER TABLE report_data
ADD COLUMN d_name {column definition} ,
ADD INDEX (d_name);
sample fiddle

Copy rows in the same table with recursive dependency inside

I have the some tables in MySQL database
create table pages
(
id bigint not null,
organization_id bigint null,
parent_id bigint null,
language_tag varchar(2) null,
type varchar(7) null,
theme varchar(19) null,
status varchar(7) null,
title varchar(256) null,
image text null,
image_hover text null,
sort int null,
created_at timestamp null,
updated_at timestamp null,
constraint pages_id_uindex
unique (id),
constraint pages_pages_id_fk
foreign key (parent_id) references pages (id)
on update cascade on delete cascade
);
create table blocks
(
id bigint null,
page_id bigint null,
title varchar(256) null,
content longtext null,
readmore longtext null,
image varchar(1024) null,
image_hover varchar(1024) null,
type char(9) null,
sort int null,
constraint blocks_pages_null_fk
foreign key (page_id) references pages (id)
);
As you can see parent_id is a reference to its own table id.
I want to copy some specific rows with all its children. I couldn't write a simple insert query because I cannot know parent_id of parent page that not existing yet. Also, relation is recursive and not plain. Some children could have another children, e.t.c Just like a tree. I could make it nullable, but then I have to update all children manually. And I have blocks relation entity that have to be copied too. It's a quite terrible amount of work. Could you give me advice how I can resolve this issue with the simplest way?

Using composite key as a foreign key in mysql

My Tables
Fee Table
CREATE TABLE IF NOT EXISTS `fee` (
`feeNumber` int(11) NOT NULL,
`feeName` varchar(255) NOT NULL,
`feeDescription` varchar(255) DEFAULT NULL,
`feeAmount` varchar(255) NOT NULL,
`universityName` varchar(255) NOT NULL
)
ADD PRIMARY KEY (`feeNumber`,`feeName`,`feeAmount`)
Housing Table
CREATE TABLE IF NOT EXISTS `housing` (
`housingOfficeNumber` int(11) NOT NULL,
`housingOfficeName` varchar(50) NOT NULL DEFAULT '',
`housingOfficeType` varchar(50) DEFAULT NULL,
`housingOfficePhone` decimal(18,0) DEFAULT NULL,
`housingOfficeRoomDeposit` varchar(50) DEFAULT NULL,
`studentStatusName` varchar(50) DEFAULT NULL,
`housingFeeNumber` int(11) NOT NULL,
`housingFeeName` varchar(255) NOT NULL,
`housingFee` int(255) DEFAULT NULL,
`hOffTrm` varchar(50) DEFAULT NULL,
`universityName` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
What I'm trying to do is reference the feeAmount,feeNumber, and feeName from the fee table and add it to the housingfee, housingfeeName, and housingFeenumber columns in the housing table. Since the feeAmount and feeName columns are not unique I decided to make a composite key out of feeNumber, feeName, and feeAmount. The only part of the composite key I really need referenced is feeAmount. feeName and feeNumber are not really important. using phpmyadmin.
No, no, no. In general, I think it is best to avoid compound primary keys. In this case, in particular, you do not want the fee amount or name to be part of the key. In order to access the row, you need to know the amount. That seems very difficult to implement.
I am guessing that an auto incremented primary key will work just fine. You can then add a separate unique constraint on other columns. So:
CREATE TABLE IF NOT EXISTS `fee` (
`feeNumber` int(11) NOT NULL auto_increment primary key,
`feeName` varchar(255) NOT NULL,
`feeDescription` varchar(255) DEFAULT NULL,
`feeAmount` varchar(255) NOT NULL,
`universityName` varchar(255) NOT NULL,
unique (feeName)
);
Then, another table would have feeNumber with an appropriate foreign key reference. Through the reference, you can get other information -- such as the name and amount -- using a join.

Create mysql table, parenthesis error: You have an error in your SQL syntax; check the manual ... for the right syntax to use near ')' at line 12

As a recent SQL learner, I've tried this piece of code for creating six tables through dozens of times, but cannot figure out what did the shell mean by saying that something is wrong near ")".
If there are obvious syntax errors, I could have fixed it.
Thank you for helping.
-- Table APPOINTMENT
CREATE TABLE APPOINTMENT (
AppointmentID INTEGER NOT NULL AUTO_INCREMENT,
DateAndTime VARCHAR(20) NULL DEFAULT NULL,
Venue VARCHAR(20) NULL DEFAULT NULL,
PatientName VARCHAR(20) NULL DEFAULT NULL,
DoctorName VARCHAR(20) NULL DEFAULT NULL,
PatientID VARCHAR(20) NOT NULL,
DoctorID VARCHAR(20) NOT NULL,
IsEmergency VARCHAR(3) DEFAULT "YES",
IsVisited VARCHAR(3) DEFAULT "YES",
PRIMARY KEY (AppointmentID),
);
-- Table PATIENT
CREATE TABLE PATIENT (
PatientID VARCHAR(20) NOT NULL,
PatientName VARCHAR(20) NULL DEFAULT NULL,
Address VARCHAR(20) NULL DEFAULT NULL,
CurrentMedication VARCHAR(20) NULL DEFAULT NULL,
ChronicDisease VARCHAR(20) NULL DEFAULT NULL,
Allergies VARCHAR(20) NULL DEFAULT NULL,
MedicalHistory VARCHAR(20) NULL DEFAULT NULL,
PRIMARY KEY (PatientID),
);
-- Table DOCTOR
CREATE TABLE DOCTOR (
DoctorID VARCHAR(20) NOT NULL,
DoctorName VARCHAR(20) NULL DEFAULT NULL,
PRIMARY KEY (DoctorID),
);
-- Table BILL
CREATE TABLE BILL (
AppointmentID INTEGER NOT NULL AUTO_INCREMENT,
DoctorID VARCHAR(20) NOT NULL,
PatientID VARCHAR(20) NOT NULL,
DateAndTime VARCHAR(20) NULL DEFAULT NULL,
Diagnosis VARCHAR(20) NULL DEFAULT NULL,
Treatment VARCHAR(20) NULL DEFAULT NULL,
Fees INTEGER NULL DEFAULT NULL,
ServiceCharge INTEGER NULL DEFAULT NULL,
ClaimId INTEGER NOT NULL,
InsuredDeduction INTEGER NULL AUTO_INCREMENT DEFAULT NULL,
ReceiptNumber INTEGER NOT NULL,
AmountPaid INTEGER NULL DEFAULT NULL,
TotalAmountDue INTEGER NULL DEFAULT NULL,
PRIMARY KEY (AppointmentID),
);
-- Table PAYMENT
CREATE TABLE PAYMENT (
ReceiptNumber INTEGER NOT NULL AUTO_INCREMENT,
AppointmentID INTEGER NOT NULL,
AmountPaid INTEGER NULL DEFAULT NULL,
PatientID VARCHAR(20) NOT NULL,
PRIMARY KEY (ReceiptNumber)
);
-- Table CLAIM
CREATE TABLE CLAIM (
ClaimId INTEGER NOT NULL AUTO_INCREMENT,
InsuranceCompanyName VARCHAR(20) NULL DEFAULT NULL,
PatientID VARCHAR(20) NOT NULL,
PRIMARY KEY (ClaimId),
);
-- Foreign Keys
ALTER TABLE APPOINTMENT ADD FOREIGN KEY (PatientID) REFERENCES PATIENT (PatientID);
ALTER TABLE APPOINTMENT ADD FOREIGN KEY (DoctorID) REFERENCES DOCTOR (DoctorID);
ALTER TABLE PAYMENT ADD FOREIGN KEY (AppointmentID) REFERENCES BILL (AppointmentID);
ALTER TABLE PAYMENT ADD FOREIGN KEY (PatientID) REFERENCES PATIENT (PatientID);
ALTER TABLE BILL ADD FOREIGN KEY (DoctorID) REFERENCES DOCTOR (DoctorID);
ALTER TABLE BILL ADD FOREIGN KEY (PatientID) REFERENCES PATIENT (PatientID);
ALTER TABLE BILL ADD FOREIGN KEY (ClaimId) REFERENCES CLAIM (ClaimId);
ALTER TABLE BILL ADD FOREIGN KEY (ReceiptNumber) REFERENCES PAYMENT (ReceiptNumber);
ALTER TABLE CLAIM ADD FOREIGN KEY (PatientID) REFERENCES PATIENT (PatientID);
You have an extra comma in every create table statement. eg PRIMARY KEY (DoctorID) has a trailing comma. MySql expects another column declaration after that comma.
-- Table DOCTOR
CREATE TABLE DOCTOR (
DoctorID VARCHAR(20) NOT NULL,
DoctorName VARCHAR(20) NULL DEFAULT NULL,
PRIMARY KEY (DoctorID)
);

#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key

I have a serial no. column which is auto increment, but I want enrollment id. to be the primary key and MySQL is just not allowing me to do that. Is there any way around to do that?
You can only define a column as AUTO_INCREMENT if it is a PRIMARY KEY and an INT (not sure of this but BIGINT will work too). Since you want the SerialNo to be set as AUTO_INCREMENT, why not make it as PRIMARY KEY and the EnrollmentID as UNIQUE?
CREATE TABLE TableName
(
SerialNo INT AUTO_INCREMENT PRIMARY KEY,
EnrollmentID INT UNIQUE,
-- other columns...
)
Make sure you define your serial number column as UNIQUE.
CREATE TABLE tbl_login (
id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
first_name varchar(100) NOT NULL,
last_name varchar(100) NOT NULL,
gender varchar(30) NOT NULL,
email varchar(200) NOT NULL,
password varchar(200) NOT NULL,
address text NOT NULL,
mobile_no varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;