Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL create temporary table with auto_increment id and select query

Tags:

sql

mysql

want to create a temporary table that has an auto_increment field plus a field that has to be select from another table.

Here is what I have (does not work)

CREATE TEMPORARY TABLE tmp  (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
(SELECT valueName AS valueName
FROM sometable
WHERE sometable.somevalue='00'));

these work by them selves but can get the right syntax to do both

CREATE TEMPORARY TABLE tmp  (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY)

CREATE TEMPORARY TABLE tmp AS SELECT valueName AS valueName FROM sometable
WHERE sometable.somevalue='00';
like image 867
user1171669 Avatar asked Jan 26 '12 16:01

user1171669


People also ask

How can insert auto increment value in SQL query?

To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.

Does MySQL auto generate ID?

Auto increment syntaxThis causes the category Id to be automatically generated every time a new row is inserted into the table. It is not supplied when inserting data into the table, MySQL generates it.

Can we have 2 auto increment in MySQL?

MySQL server already provides two auto increment variables: auto_increment_increment and auto_increment_offset, which can be used to generate different auto increment values on each member.

How do I add an auto increment to an existing table?

If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.


1 Answers

I think you might be trying to do the first case outlined here:

http://dev.mysql.com/doc/refman/5.5/en/create-table-select.html

..which for your example would look like:

CREATE TEMPORARY TABLE tmp (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY) 
SELECT valueName AS valueName FROM sometable
WHERE sometable.somevalue='00';

..so it might just be the parens in the wrong places that bit you in your first try.

like image 159
Andrew Avatar answered Oct 11 '22 15:10

Andrew