I want to copy all the fields from the temp_sales table to sales table (after specific field). I want to do it quickest way as possible.. How to do this in SQL?
CREATE TABLE IF NOT EXISTS `temp_sales` (
`field1` varchar(10) NOT NULL,
`field2` varchar(20) NOT NULL,
`field3` varchar(20) NOT NULL,
`field4` varchar(50) NOT NULL,
`field5` varchar(50) NOT NULL,
`field6` varchar(50) NOT NULL,
`field7` varchar(50) NOT NULL,
`field8` tinyint(2) NOT NULL,
`field9` tinyint(2) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=13692 ;
In other word: There are some fields in the sales table. I want to add more new fields in the sales table from temp_sales (without data).
This is a 3-Step process:
.1. You need some unique or primary key field in temp_sales, that links a row in temp_sales to the corresponding row in sales (again via a unique/primary key)
.2. You need a DDL statement such as
ALTER TABLE `sales`
ADD COLUMN `field1`VARCHAR(10) AFTER `whatever`,
ADD COLUMN `field2`VARCHAR(10) AFTER `fields2`,
...
.3. You need a DML statement such as
UPDATE `sales`
INNER JOIN `temp_sales` ON `sales`.`keyfield`=`temp_sales`.`keyfield`
SET `sales`.`field1`=`tempsales`.`field1`,
`sales`.`field2`=`tempsales`.`field2`,
...
You can do this:
mysql> create table new_table_name as(select * from existing_table_name);
//It will also populate existing table data to new table if present
//If old table is empty then it will create same copy of that table
In your case:
mysql> create table sales as(select * from temp_sales);
Related
I wanted to use the value on student_lastname in table tbl_student as a default value of sis_password in
table tbl_sis_account but I am out of idea on how to do it. I tried putting "Select query" after the "Default" but it doesn'nt work, anyway here's the sql:
DROP TABLE IF EXISTS tbl_sis_account;
CREATE TABLE `tbl_sis_account`(
sis_account_id INT(15) NOT NULL AUTO_INCREMENT,
sis_username INT(15) NOT NULL,
sis_password VARCHAR(8) DEFAULT '====>Value of attribute student_lastname<====',
PRIMARY KEY(`sis_account_id`),
CONSTRAINT `sis_username_student_fk` FOREIGN KEY (`sis_username`) REFERENCES `tbl_student`
(`student_id`) ON UPDATE CASCADE
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
SELECT * FROM tbl_sis_account;
DROP TABLE IF EXISTS tbl_student;
CREATE TABLE `tbl_student` (
`student_id` INTEGER(15) NOT NULL AUTO_INCREMENT,
`student_firstname` VARCHAR(50) NOT NULL,
`student_midname` VARCHAR(50) NOT NULL,
`student_lastname` VARCHAR(50) NOT NULL,
PRIMARY KEY(`student_id`)
)ENGINE=INNODB AUTO_INCREMENT=20201 DEFAULT CHARSET=utf8mb4;
SELECT * FROM tbl_student;
No you can't do that, but you can query the tbl_student table at the time of insertion in the tbl_sis_account table to retrieve student_lastname from `student_id' via a nested sql query or a trigger.
I've figured the solution for this problem, for a while now. Forgot to post the answer though, coz I am no longer using this method. But here's what I did.
On the tbl_student I created a "After Insert trigger"
BEGIN
INSERT INTO tbl_sis_account (student_id,sis_password) values (new.student_id, concat(new.student,new.student_lastname));
END
so the inserted result on tbl_sis_account is
student_id | sis_password
20200001 | 202000001Doe
I want to create a table name Users where I should have have columns User, cookieID, sessionID, Geo and then I want to first three columns to have some random unique value assigned automatically. I tried to make all three columns AUTO_INCREMENT with User column PRIMARY and 'cookieIDandsessionIDcolumnUNIQUE`. The SQL code is:
CREATE TABLE `users` ( `User` VARCHAR(20) NOT NULL AUTO_INCREMENT ,
`cookieID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`sessionID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`Geo` VARCHAR(30) NULL DEFAULT NULL ,
PRIMARY KEY (`User`), UNIQUE (`cookieID`), UNIQUE (`sessionID`), UNIQUE (`Geo`));
But, it did not work because only one column can be declared as AUTO_INCREMENT which must be PRIMARY.
What is the another approach to do this?
Since the auto-increment cannot be applied to multiple to rows and there no option for sequence in MySQL. You can use triggers for the unique update of the row with datetime.
Change to table creation to be of single auto-increment row.
CREATE TABLE `users` ( `User` VARCHAR(20) NOT NULL,
`cookieID` INT(20) NULL DEFAULT NULL,
`sessionID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`Geo` VARCHAR(30) NULL DEFAULT NULL,
PRIMARY KEY (`User`), UNIQUE (`cookieID`), UNIQUE (`sessionID`), UNIQUE (`Geo`));
Create a trigger on the same table as below. You can set the unique values under the SET for as many column as you want.
CREATE DEFINER=`root`#`localhost` TRIGGER `users_BEFORE_INSERT` BEFORE INSERT ON `users` FOR EACH ROW BEGIN
SET
NEW.cookieID = (SELECT curdate()+curtime());
END
Now when you insert into the table as below.
insert into `users`(`User`) values("test");
You table looks like this.
User cookieID sessionID Geo
test 20315169 0 NULL
If the value which are auto incrementing, you wanna keep both values the same. Then copy the value of one column to another during insertion time of new value.
I have been successful in adding a new column to my table in MySQL. However I can't seem to add any data to it. I have tried using an UPDATE but I get an error. I am including the original code for the table, and the ALTER that added the column and the attempted update.
CREATE TABLE `Teams` (
`Team_id` INTEGER unsigned NULL AUTO_INCREMENT DEFAULT NULL,
`team name` VARCHAR(50) NULL DEFAULT NULL,
`league` CHAR(2) NULL DEFAULT NULL,
`div` VARCHAR(15) NULL DEFAULT NULL,
PRIMARY KEY (`Team_id`)
);
the filling (abbreviated)
INSERT INTO `Teams` (`team name`,`league`,`div`) VALUES
('Free Agent','',''),
('Blue Jays','AL','East'),
('Yankees','AL','East'),
('Orioles','AL','East'),
...and so on
The ALTER:
ALTER TABLE Teams
ADD City VARCHAR(20);
The UPDATE:
UPDATE Teams
SET City='NONE' where (team name='Free Agent');
You should escape identifiers if they contain spaces:
UPDATE `Teams`
SET `City`='NONE' where (`team name`='Free Agent');
I have two tables with the following schema,
CREATE TABLE `open_log` (
`delivery_id` varchar(30) DEFAULT NULL,
`email_id` varchar(50) DEFAULT NULL,
`email_activity` varchar(30) DEFAULT NULL,
`click_url` text,
`email_code` varchar(30) DEFAULT NULL,
`on_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `sent_log` (
`email_id` varchar(50) DEFAULT NULL,
`delivery_id` varchar(50) DEFAULT NULL,
`email_code` varchar(50) DEFAULT NULL,
`delivery_status` varchar(50) DEFAULT NULL,
`tries` int(11) DEFAULT NULL,
`creation_ts` varchar(50) DEFAULT NULL,
`creation_dt` varchar(50) DEFAULT NULL,
`on_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The email_id and delivery_id columns in both tables make up a unique key.
The open_log table have 2.5 million records where as sent_log table has 0.25 million records.
I want to filter out the records from open log table based on the unique key (email_id and delivery_id).
I'm writing the following query.
SELECT * FROM open_log
WHERE CONCAT(email_id,'^',delivery_id)
IN (
SELECT DISTINCT CONCAT(email_id,'^',delivery_id) FROM sent_log
)
The problem is the query is taking too much time to execute. I've waited for an hour for the query completion but didn't succeed.
Kindly, suggest what I can do to make it fast since, I have the big data size in the tables.
Thanks,
Faisal Nasir
First, rewrite your query using exists:
SELECT *
FROM open_log ol
WHERE EXISTS (SELECT 1
FROM send_log sl
WHERE sl.email_id = ol.email_id and sl.delivery_id = ol.delivery_id
);
Then, add an index so this query will run faster:
create index idx_sendlog_emailid_deliveryid on send_log(email_id, delivery_id);
Your query is slow for a variety of reasons:
The use of string concatenation makes it impossible for MySQL to use an index.
The select distinct in the subquery is unnecessary.
Exists can be faster than in.
If this request is often on, you can greatly increase it by create bigint id column, enven if it not unique.
For example you can put trigger and create column like this
alter table sent_log for_get bigint;
After that create trigger/ update it to put hash into that bigint
for_get=CONV(substr(md5(concat(email_id, delivery_id)),1,10),16,10)
If you have such column in both table and index on it, query will be like
SELECT *
FROM open_log ol
left join send_log sl on sl.for_get=ol.for_get
WHERE sl.email_id is not null and sl.email_id = ol.email_id and sl.delivery_id = ol.delivery_id;
That query will be fast.
I have a table in which there is a column name with SP varchar(10) NOT NULL. I want that column always to be unique so i created unique index on that column . My table schema as follows :
CREATE TABLE IF NOT EXISTS `tblspmaster` (
`CSN` bigint(20) NOT NULL AUTO_INCREMENT,
`SP` varchar(10) NOT NULL,
`FileImportedDate` date NOT NULL,
`AMZFileName` varchar(50) NOT NULL,
`CasperBatch` varchar(50) NOT NULL,
`BatchProcessedDate` date NOT NULL,
`ExpiryDate` date NOT NULL,
`Region` varchar(50) NOT NULL,
`FCCity` varchar(50) NOT NULL,
`VendorID` int(11) NOT NULL,
`LocationID` int(11) NOT NULL,
PRIMARY KEY (`CSN`),
UNIQUE KEY `SP` (`SP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10000000000 ;
Now i want that if anybody tries to insert duplicate record then that record should be inserted into a secondary table name tblDuplicate.
I have gone through this question MySQL - ignore insert error: duplicate entry but i am not sure that instead of
INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200;
can i insert duplicate row into another table ?
what changes needed to be done in main table scheme or index column ?
**Note : Data will be inserted by importing excel or csv files and excel files generally contains 500k to 800 k records but there will be only one single column **
I believe you want to use a trigger for this. Here is the MySQL reference chapter on triggers.
Use a before insert trigger. In the trigger, check if the row is a duplicate (maybe count(*) where key column value = value to be inserted). If the row is a duplicate, perform an insert into your secondary table.