This question already has answers here:
SELECT INTO in MySQL
(2 answers)
Closed 5 years ago.
I'm trying to move a select statement's result into a new non-existent table but not able to figure how.
In MS SQL, I would be following the below,
SELECT * INTO <NON_EXISTING_TABLE> FROM
(
SELECT * FROM TABLE1 A
JOIN TABLE2 B
ON A.DescriptionNo = B.DescriptionNo
WHERE A.DescriptionNo =1) A
When i quickly looked it up , I can see only answers to insert data into an existing table but not dynamically create a new table with the result of the statement.
Please advice !
If you want to create a new table from a select, you can use this syntax:
create table new_table as
select *
from existing_table
where ...
This solution showed above works perfect also for selected rows. For example I am creating demonstration rows for my nice2work project, and this works perfect.
CREATE TEMPORARY TABLE tmptable SELECT * FROM myTable WHERE id=500;
UPDATE tmptable SET id = 0;
UPDATE some fields I need to change
INSERT INTO myTable SELECT * FROM tmptable;
DROP TABLE tmptable;
// You can use this same also directly into your code like (PHP Style)
$sql = "CREATE TEMPORARY TABLE tmptable SELECT * FROM myTable WHERE id=500;
UPDATE tmptable SET id = 0;
UPDATE some fields I need to change
INSERT INTO myTable SELECT * FROM tmptable;DROP TABLE tmptable;";
Related
This question already has answers here:
MySQL: Insert record if not exists in table [duplicate]
(16 answers)
Closed 7 years ago.
I have two tables event and guest and an eventGuest table that joins them together and has some information about the guest (like if they attended etc) and am trying to insert into the eventGuest table without creating a duplicate sort of like:
insert into eventGuest(eventID, GuestID, attended)
values(iEventID, iGuestID, bAttended)
where (select count(*) from eventGuest where eventID = iEventID and guestID = iGuestID) = 0
Copy one table data to another :-
INSERT INTO TARGET_TABLE (`col1`,`col2`) SELECT `col1`,`col2` FROM SOURCE_TABLE;
You should use INSERT INTO ... SELECT if you want to insert values from a table into another:
INSERT INTO eventGuest(eventID, GuestID, attended)
SELECT iEventID, iGuestID, bAttended
FROM Anothertable t
where NOT EXIST(select 1
from eventGuest e
where e.eventID = t.iEventID
and e.guestID = t.iGuestID);
Or, if you want to insert into the same table if the values of eventid and iGuestid doesn't exist, you can do this:
INSERT INTO eventGuest(eventID, GuestID, attended)
SELECT *
FROM ( SELECT 'eventid', 'guestid', 'somevalue' ) AS t
WHERE NOT EXISTS (
SELECT 1 FROM eventGuest e
WHERE e.eventID ='eventid'
and e.guestID = 'guestid'
) LIMIT 1;
Please do add a unique constraint in the eventGuest table for both eventid and guestid and use INSERT IGNORE or REPLACE command to insert the new data.
This question already has answers here:
In MySQL, can I copy one row to insert into the same table?
(26 answers)
Closed 7 years ago.
A great way to duplicate a row in MySQL is to use INSERT INTO ... SELECT FROM syntax.
For example:
INSERT INTO tblExample (col1, col2, col3)
SELECT col1, col2, col3 FROM tblExample WHERE pkey = 1234;
This is easy and straightforward, but from a code maintenance standpoint this is one more statement to keep track of if there are any schema changes. Suppose I add an additional column to the tblExample table, col4; now I have to remember to go back and update this SQL statement in my code. If I fail to do so, then I've just introduced a bug.
With this in mind, is there an easy to way to copy the whole row, whatever the schema may be, except for the primary key?
Very much against best practices you can do the following:
INSERT INTO myTable
SELECT * FROM myTable WHERE thisField = "abcd"
A somewhat inelegant way:
CREATE TEMPORARY TABLE tmpTable ENGINE=MEMORY SELECT * FROM realTable WHERE pk = 'something';
UPDATE tmpTable SET pk = 'something else' ;
INSERT INTO realTable SELECT * FROM tmpTable;
I have two databases, test1 & test2. In test1 there is a table attendence, I want to copy this attendece table in database test2. I am writing following code:
CREATE TABLE test1.attendence SELECT * FROM test2.attendence;
But it gives the error:
--Table 'test2.attendence' doesn't exist
So please provide a way to do it.
insert into table2 select * from table1
or if they dont have the same structure:
insert into table2 (col, col2, col5) select (x,y,z) from table1
CREATE TABLE x LIKE other_db.y;
INSERT INTO x SELECT * FROM other_db.y;
you're almost there :)
but you want to create the new table in test2, so, the correct command should be
CREATE TABLE test2.attendence LIKE test1.attendence;
INSERT INTO test2.attendence SELECT * FROM test1.attendence;
I am tring to do this
Get all rows in a blogs named table.
Copy them in a temporary database
Edit the language field of this temporary table records
Insert into the blogs table
And I'm trying it like this:
CREATE TEMPORARY TABLE tmptable SELECT * FROM blogs WHERE lan = 2;
UPDATE tmptable SET lan = 1;
INSERT INTO blogs SELECT * FROM tmptable; dump database tmptable;
But of corse I get duplicated key error...
How Can I prevent it?
-EDIT-
I TRIED:
CREATE TEMPORARY TABLE tmptable SELECT * FROM blogs WHERE lan = 2;
UPDATE tmptable SET lan = 1;
ALTER TABLE tmptable DROP id;
INSERT INTO blogs SELECT * FROM tmptable; dump database tmptable;
But then the Column count doesn't match value count at row 1
-EDIT-
I believe this will work (And it Did, cause I know how many records exist)
CREATE TEMPORARY TABLE tmptable SELECT * FROM blogs WHERE lan = 2;
UPDATE tmptable SET lan = 1;
UPDATE tmptable SET id = id + 1000;
INSERT INTO blogs SELECT * FROM tmptable;
But how can I do it properly? (just set the next avaliable autoincrement value for primary key(id) (without PHP/alike))
-EDIT-
maybe something like this???
CREATE TEMPORARY TABLE tmptable SELECT * FROM blogs WHERE lan = 2;
UPDATE tmptable SET lan = 1;
UPDATE tmptable SET id = id + (SELECT id FROM blogs ORDER BY id DESC LIMIT 1);
INSERT INTO blogs SELECT * FROM tmptable;
No temporary table needed.
INSERT INTO blogs (lan, col1, col2, col3, ...)
SELECT 1, col1, col2, col3, ...
FROM blogs
WHERE lan = 2
Replace col1, col2, col3, ... with a list of all columns except lan and id.
CREATE TEMPORARY TABLE tmptable SELECT * FROM blogs WHERE lan = 2;
UPDATE tmptable SET lan = 1;
alter table tmptable drop column id;
INSERT INTO blogs SELECT NULL,tmptable.* FROM tmptable;
Assumed, the column "id" is the first col.
UPDATE blogs SET lan = 1 WHERE lan = 2;
Simply run that query on your original table.
I don't want to change the language, I want to save another copy of
all the records and asign this copies a different language
In that case, drop the primary key from your temporary table. When you insert back the rows, don't include the primary key column:
INSERT INTO blogs (title, lan) SELECT * FROM tmptable;
Please try following sql. A similar SQL FIDDLE
CREATE TEMPORARY TABLE tmptable SELECT * FROM blogs WHERE lan = 2;
UPDATE tmptable SET lan = 1;
UPDATE tmptable SET id = (select #val:=#val+1 from(select #val:=(select max(id) from blogs)) t)
INSERT INTO blogs SELECT * FROM tmptable;
Hope this helps.
Using prepared statement you can query the information schema for the column you want to use and then forge the query you want to execute:
here an example for your case:
-- first query all the blogs column minus id and lan
SELECT GROUP_CONCAT(c.COLUMN_NAME)
INTO #cols
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE
c.TABLE_NAME = 'blogs'
AND c.COLUMN_NAME not in ('id', 'lan');
-- second build the query with the gathered columns
-- like INSERT INTO blogs(lan, col1, ...) SELECT 2, col1, ... FROM blogs WHERE lan=1
SET #sql=CONCAT(CONCAT(CONCAT(CONCAT('INSERT INTO blogs (lan,', #cols),
') SELECT 2,'), #cols), ' FROM blogs WHERE lan=1');
-- prepare the statement
PREPARE stmt FROM #sql;
-- and last run the insert
EXECUTE stmt;
I need to query a delete statement for the same table based on column conditions from the same table for a correlated subquery.
I can't directly run a delete statement and check a condition for the same table in mysql for a correlated subquery.
I want to know whether using temp table will affect mysql's memory/performance?
Any help will be highly appreciated.
Thanks.
You can make mysql do the temp table for you by wrapping your "where" query as an inline from table.
This original query will give you the dreaded "You can't specify target table for update in FROM clause":
DELETE FROM sametable
WHERE id IN (
SELECT id FROM sametable WHERE stuff=true
)
Rewriting it to use inline temp becomes...
DELETE FROM sametable
WHERE id IN (
SELECT implicitTemp.id from (SELECT id FROM sametable WHERE stuff=true) implicitTemp
)
Your question is really not clear, but I would guess you have a correlated subquery and you're having trouble doing a SELECT from the same table that is locked by the DELETE. For instance to delete all but the most recent revision of a document:
DELETE FROM document_revisions d1 WHERE edit_date <
(SELECT MAX(edit_date) FROM document_revisions d2
WHERE d2.document_id = d1.document_id);
This is a problem for MySQL.
Many examples of these types of problems can be solved using MySQL multi-table delete syntax:
DELETE d1 FROM document_revisions d1 JOIN document_revisions d2
ON d1.document_id = d2.document_id AND d1.edit_date < d2.edit_date;
But these solutions are best designed on a case-by-case basis, so if you edit your question and be more specific about the problem you're trying to solve, perhaps we can help you.
In other cases you may be right, using a temp table is the simplest solution.
can't directly run a delete statement and check a condition for the same table
Sure you can. If you want to delete from table1 while checking the condition that col1 = 'somevalue', you could do this:
DELETE
FROM table1
WHERE col1 = 'somevalue'
EDIT
To delete using a correlated subquery, please see the following example:
create table project (id int);
create table emp_project (id int, project_id int);
insert into project values (1);
insert into project values (2);
insert into emp_project values (100, 1);
insert into emp_project values (200, 1);
/* Delete any project record that doesn't have associated emp_project records */
DELETE
FROM project
WHERE NOT EXISTS
(SELECT *
FROM emp_project e
WHERE e.project_id = project.id);
/* project 2 doesn't have any emp_project records, so it was deleted, now
we have 1 project record remaining */
SELECT * FROM project;
Result:
id
1
Create a temp table with the values you want to delete, then join it to the table while deleting. In this example I have a table "Games" with an ID column. I will delete ids greater than 3. I will gather the targets in a temp table first so I can report on them later.
DECLARE #DeletedRows TABLE (ID int)
insert
#DeletedRows
(ID)
select
ID
from
Games
where
ID > 3
DELETE
Games
from
Games g
join
#DeletedRows x
on x.ID = g.ID
I have used group by aggregate with having clause and same table, where the query was like
DELETE
FROM TableName
WHERE id in
(select implicitTable.id
FROM (
SELECT id
FROM `TableName`
GROUP by id
HAVING count(id)>1
) as implicitTable
)
You mean something like:
DELETE FROM table WHERE someColumn = "someValue";
?
This is definitely possible, read about the DELETE syntax in the reference manual.
You can delete from same table. Delete statement is as follows
DELETE FROM table_name
WHERE some_column=some_value