set auto increment initial value for mysql table - mysql

I'm trying to create a table in my sql using PHP but I'm not sure how to set an initial value for the auto increment field.
This is what i have so far:
function create_table($db_host,$db_user,$db_pswrd,$db_name){
$connect = mysql_connect($db_host,$db_user,$db_pswrd) or die(mysql_error());
mysql_select_db($db_name, $connect);
$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)
)"or die(mysql_error());
mysql_query($sql,$connect)or die(mysql_error());
mysql_close($connect);
}
So i need to know how to set the initial Auto Increment value on this table, upon creation?
Thanks

If you don't have the auto-increment column in the table yet:
$sql = "ALTER TABLE MY_TABLE ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT,
ADD INDEX (id);";
Then to set the auto-increment starting value:
$sql = "ALTER TABLE MY_TABLE AUTO_INCREMENT = 111111;";
Potential duplicate of this post.

Assuming your auto increment column is the first one:
$sql = "CREATE TABLE MY_TABLE
(
table_1 INT AUTO_INCREMENT,
table_2 varchar(45),
table_3 varchar(999),
table_4 varchar(45)
) AUTO_INCREMENT = 231";
The starting value will be, here, 231.
I changed the column type to INT, because you can't use a VARCHAR for auto-increment.
(and remove the or die(mysql_error()) on this line btw, its pointless because it's just a variable creation, not a SQL query being executed)

Related

SQL : Insert Or Update command

I am using "Voila Norbert" API and I would like to store results in a DB table like this :
email_Norbert (
id Integer(11) NOT NULL AUTO_INCREMENT,
idUser Integer(11) NOT NULL,
email VarChar(50) CHARACTER SET latin1 COLLATE latin1_swedish_ci,
score Integer(2),
existence TinyInt(1),
PRIMARY KEY (
id
)
Actually I use this query (as an example, I set values but it changes everytime for each idUser) :
INSERT INTO email_Norbert (idUser,email,score)
VALUES (2 ,'MyEmailHere',100)
ON DUPLICATE KEY UPDATE idUser = 2,email = 'MyEmailHere', score = 100
The insert run well but when the record already exist, I does add an other record.
What should I do ?
if you want subsequent inserts for same user to fail and instead update, add a unique index on the iduser column.
create unique index email_Norbert_u1 on email_Norbert(iduser)

how to set the auto_increment starting value in MySQL using SQL?

I have tried several ways of setting the auto increment value on the primary key ID on a table with no luck.
Doesn't work for me...
id INT NOT NULL AUTO_INCREMENT = 10000,
Tried this...
UPDATE tablename SET id = id + 10000;
Tried this..
ALTER TABLE tablename AUTO_INCREMENT = 10000;
Tried this..
CREATE TABLE tablename (
...
) ENGINE = MyISAM AUTO_INCREMENT = 10000;
What is the proper way to set this when creating a table using SQL?
On the creation of the table you can use these SQL statement:
CREATE TABLE tablename (
...
) ENGINE = InnoDB AUTO_INCREMENT = 10000;
But, if the table is already created, you can make an ALTER TABLE to let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
ALTER TABLE tablename AUTO_INCREMENT = 10000;
You can find more on using AUTO_INCREMENT.

Copy column definition from one table to another?

I want to copy a column (definition, not data) from one table to another. Add the column if it doesn't exist in destination table, or better yet, modify it accordingly if it exists.
Tried to google but everything seems to be about either copying the data rather than the definition, or about copying an entire table using CREATE TABLE ... LIKE ....
Thus far the closest I could find is this:
CREATE TABLE table2 AS
SELECT field4, field7 -- only the columns you want
FROM table
WHERE FALSE; -- and no data
But I need to copy columns to existing tables. So I tried:
ALTER TABLE table2 AS
SELECT field4, field7 -- only the columns you want
FROM table
WHERE FALSE; -- and no data
But apparently it refused to work.
Is there something like this?
ALTER TABLE table1 ADD COLUMN column2 LIKE table2.column5
Any way to achieve this in MySQL?
The best way is to Dump the table and then you can use ALTER command to create the new table.
Dumping the table gives back the query to CREATE the table.
CREATE TABLE IF NOT EXISTS customer (
id int(11) NOT NULL AUTO_INCREMENT,
customerId varchar(50) NOT NULL,
firstName varchar(30) NOT NULL,
middleName varchar(30) DEFAULT NULL,
lastName varchar(30) CHARACTER SET utf8 COLLATE utf8_estonian_ci DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
USE the same to ALTER an existing table, (say customerinfo)
`ALTER TABLE customerinfo ADD COLUMN (
customerId varchar(50) NOT NULL,
firstName varchar(30) NOT NULL,
middleName varchar(30) DEFAULT NULL,
lastName varchar(30) CHARACTER SET utf8 COLLATE utf8_estonian_ci DEFAULT NULL
)
If you want to do it with queries this is the way:
Get the properties of the old column with:
SHOW COLUMNS FROM `mytable` where Field=`mycolumn`
Use mysqli_fetch_array to get the field properties in the variable $row.
Now create the new query:
$qry = "ALTER TABLE othertable";
$qry .= " ADD `newcol`"; /* name of new column; $row['Field'] works too */
$qry .= " ".$row["Type"]; /* example value: varchar(255) */
if($row["Null"] == "NO")
$qry .= " NOT NULL";
if($row["Default"] != "")
$qry .= " default '".$row["Default"]."'";
The $row contains also an Extra field but that can give problems with auto_increase.

Add column with FK to an existing table in MySQL 5.6

Good day everyone. Hope someone can helps me in my experiments.
I have a simple Table for my needs and it's even have some data inside.
CREATE TABLE IF NOT exists main.test (
ID INT(11) NOT NULL,
NAME varchar(30) NOT NULL,
DATE_CREATED timestamp NOT NULL,
PRIMARY KEY (ID));
But then I should update this table with adding column FK_.
How can I check if table had already has field FK_?
If such column is not exist do:
ALTER TABLE main.test
ADD COLUMN FK INT(11),
ADD FOREIGN KEY (FK)
REFERENCES test2(ID_test2)
As I use java decision of my problem was using ResultSet.
ResultSet set = statement.executeQuery(query);
set.next();
int result = set.getInt(1); //it always return only one row
set.close();
And this is my sql-query:
SELECT COUNT(COLUMN_NAME) FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'main'
AND TABLE_NAME = 'test'
AND COLUMN_NAME = 'FK";
When I'll get a result I can decide what query I should to use.

SQL Table Decode from a SQL query

I have a sql query,
$sql = "select
tbl_user.name,chat.from,chat.message,chat.to,chat.id,chat.sent,chat.recd
from chat,tbl_user where (chat.to =
'".mysql_real_escape_string($_SESSION['chatuser'])."' AND recd = 0) and
chat.from=tbl_user.user_id order by id ASC";
But i dont know how to create a table from this information. The above is
a select table syntax, but can anyone help me to make the above sql query
to a proper syntax, so that i can create the table.
Example, i need the ab0ve t0 like this
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
You can use the CREATE TABLE new_tbl AS SELECT ...
Read the documentation for MySql:
http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html