I have been looking for the answer to the question below:
MySQL: Insert record if not exists in table
I have an extra question to the accepted answer. However, I don't have enough reputation to comment on the page...
In the answer, Mike create the table like this:
CREATE TABLE `table_listnames` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`tele` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
Is InnoDB a must, according to the query issued below? (also quoted from the answer)
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'John', 'Doe', '022') AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'John'
) LIMIT 1;
Thanks.
No, it is not necessary.
But I prefer to write your query this way:
INSERT INTO table_listnames (name, address, tele)
SELECT 'John', 'Doe', '022' FROM dual
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'John'
);
or even better, set an unique constraint:
ALTER TABLE table_listnames ADD UNIQUE (name)
and just insert with this:
INSERT INTO table_listnames (name, address, tele)
VALUES ('John', 'Doe', '022')
if a row with the name John is already present, the INSERT will simply fail.
Related
I am replacing auto_increment id with my own(of sequential and auto generated from a base number). I used ALTER TABLE tablename AUTO_INCREMENT = 701.
MySQL produced duplicates(ones with auto generated from "1" and (another sets from "701. Please see the scripts as below: Kindly help me to avoid MYSQL generated rows. Much obliged.
use login_db;
show databases;
CREATE TABLE logtable
(
id int NOT NULL AUTO_INCREMENT, accountno char(8) not null, PRIMARY KEY (id),
username VARCHAR(20) NOT NULL,
password varchar(20),
firstname varchar(8),
lastname varchar(8),
email varchar(30)
);
alter table logtable AUTO_INCREMENT = 701;
insert into logtable (username,password,firstname,lastname,email) values
('kamitrust','rust8115','john','lee','support#poosung.com');
Select * from logtable;
insert into logtable (username,password,firstname,lastname,email) values ('pinktop','winston19','jeff','kim','aol#poosung.com');
Select * from logtable;
The result from executing the script above:
# id, accountno, username, password, firstname, lastname, email
'1', '', 'kamitrust', 'rust8115', 'john', 'lee', 'support#poosung.com'
'2', '', 'pinktop', 'winston19', 'jeff', 'kim', 'aol#poosung.com'
'701', '', 'kamitrust', 'rust8115', 'john', 'lee', 'support#poosung.com'
'702', '', 'pinktop', 'winston19', 'jeff', 'kim', 'aol#poosung.com'
I've got a newbie question...
I've got two tables:
parentTable
-----------
id_user int(11) not null auto increment primary key,
email varchar(64),
pass varchar(64)
childTable
----------
id_user int(11) not null,
name varchar(64),
address varchar(512),
foreign key (id_user) references parentTable(id_user)
on update cascade
on delete restrict
Now can I insert:
insert into childTable (id_user) select id_user from parentTable where id_user = '1'
But I just want to insert also name and address values.
Sorry for the newbie question, but I lurked for a day and found nothing.
Thank you in advance for your reply.
The interesting part about your query is that you know the id_user you're trying to select to insert - it's in your WHERE clause.
If you will always know the id_user, you can skip the extra SELECT portion of the query and directly do:
INSERT INTO childTable (id_user, name, address) VALUES (1, 'some name', '123 test street');
If you, for some other reason, need the additional SELECT, you can append the name/address values directly into the field-list, like this:
INSERT INTO childTable (id_user, name, address)
SELECT id_user, 'some name', '123 test street' FROM parentTable WHERE id_user = '1';
CREATE TABLE IF NOT EXISTS `MyTable` (
`ID` SMALLINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO MyTable (ID,Name) VALUES (ID=4,Name='xxx')
or
INSERT INTO MyTable (Name) VALUES (Name='xxx')
The problem is that both INSERT statements produce the entry (4,0). Why 0 instead of "xxx"?
UPDATE: Primary key changed.
This should do the job :
INSERT INTO MyTable (ID, Name) VALUES (4, 'xxx')
I'm pretty sure it would be something like this, instead...
INSERT INTO MyTable (Name) VALUES ('xxx')
No need for the Name= part, since you've already specified which column you wish to insert into with the first (Name) definition.
Because the expression Name='xxx' is false, hence evaluates as zero.
You use the column=expression method use in on duplicate key update clauses as described here, not in the "regular" section of inserts. An example of that:
insert into mytable (col1,col2) values (1,2)
on duplicate key update col1 = col1 + 1
You should be using the syntax:
INSERT INTO MyTable (ID,Name) VALUES (4,'xxx')
Is that syntax of Name='xxx' valid? Never seen it before, i assume it is seeing it as an unquoted literal, trying to convert it to a number and coming up with 0? I'm not sure at all
Try this:
INSERT INTO MyTable (Name) VALUES ('xxx')
This is because you should mention the name of the column in the values part. And also because you do not define you primary key correctly (airlineID is not part of the field list)
CREATE TABLE IF NOT EXISTS `MyTable` (
`ID` SMALLINT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO MyTable (ID,Name) VALUES (4,'xxx')
INSERT INTO MyTable (Name) VALUES ('xxx')
Try this
INSERT INTO MyTable (ID,Name) VALUES (4,xxx)
For more Info just visit this link
I am trying to insert a new row and set the customer_id with max()+1. The reason for this is the table already has a auto_increatment on another column named id and the table will have multiple rows with the same customer_id.
With this:
INSERT INTO customers
( customer_id, firstname, surname )
VALUES
((SELECT MAX( customer_id ) FROM customers) +1, 'jim', 'sock')
...I keep getting the following error:
#1093 - You can't specify target table 'customers' for update in FROM clause
Also how would I stop 2 different customers being added at the same time and not having the same customer_id?
You can use the INSERT ... SELECT statement to get the MAX()+1 value and insert at the same time:
INSERT INTO
customers( customer_id, firstname, surname )
SELECT MAX( customer_id ) + 1, 'jim', 'sock' FROM customers;
Note: You need to drop the VALUES from your INSERT and make sure the SELECT selected fields match the INSERT declared fields.
Correct, you can not modify and select from the same table in the same query. You would have to perform the above in two separate queries.
The best way is to use a transaction but if your not using innodb tables then next best is locking the tables and then performing your queries. So:
Lock tables customers write;
$max = SELECT MAX( customer_id ) FROM customers;
Grab the max id and then perform the insert
INSERT INTO customers( customer_id, firstname, surname )
VALUES ($max+1 , 'jim', 'sock')
unlock tables;
Use alias name for the inner query like this
INSERT INTO customers
( customer_id, firstname, surname )
VALUES
((SELECT MAX( customer_id )+1 FROM customers cust), 'sharath', 'rock')
SELECT MAX(col) +1 is not safe -- it does not ensure that you aren't inserting more than one customer with the same customer_id value, regardless if selecting from the same table or any others. The proper way to ensure a unique integer value is assigned on insertion into your table in MySQL is to use AUTO_INCREMENT. The ANSI standard is to use sequences, but MySQL doesn't support them. An AUTO_INCREMENT column can only be defined in the CREATE TABLE statement:
CREATE TABLE `customers` (
`customer_id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(45) DEFAULT NULL,
`surname` varchar(45) DEFAULT NULL,
PRIMARY KEY (`customer_id`)
)
That said, this worked fine for me on 5.1.49:
CREATE TABLE `customers` (
`customer_id` int(11) NOT NULL DEFAULT '0',
`firstname` varchar(45) DEFAULT NULL,
`surname` varchar(45) DEFAULT NULL,
PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
INSERT INTO customers VALUES (1, 'a', 'b');
INSERT INTO customers
SELECT MAX(customer_id) + 1, 'jim', 'sock'
FROM CUSTOMERS;
insert into table1(id1) select (max(id1)+1) from table1;
Use table alias in subquery:
INSERT INTO customers
( customer_id, firstname, surname )
VALUES
((SELECT MAX( customer_id ) FROM customers C) +1, 'jim', 'sock')
None of the about answers works for my case. I got the answer from here, and my SQL is:
INSERT INTO product (id, catalog_id, status_id, name, measure_unit_id, description, create_time)
VALUES (
(SELECT id FROM (SELECT COALESCE(MAX(id),0)+1 AS id FROM product) AS temp),
(SELECT id FROM product_catalog WHERE name="AppSys1"),
(SELECT id FROM product_status WHERE name ="active"),
"prod_name_x",
(SELECT id FROM measure_unit WHERE name ="unit"),
"prod_description_y",
UNIX_TIMESTAMP(NOW())
)
Your sub-query is just incomplete, that's all. See the query below with my additions:
INSERT INTO customers ( customer_id, firstname, surname )
VALUES ((SELECT MAX( customer_id ) FROM customers) +1), 'jim', 'sock')
You can't do it in a single query, but you could do it within a transaction. Do the initial MAX() select and lock the table, then do the insert. The transaction ensures that nothing will interrupt the two queries, and the lock ensures that nothing else can try doing the same thing elsewhere at the same time.
We declare a variable 'a'
SET **#a** = (SELECT MAX( customer_id ) FROM customers) +1;
INSERT INTO customers
( customer_id, firstname, surname )
VALUES
(**#a**, 'jim', 'sock')
This is select come insert sequel.
I am trying to get serial_no maximum +1 value and its giving correct value.
SELECT MAX(serial_no)+1 into #var FROM sample.kettle;
Insert into kettle(serial_no,name,age,salary) values (#var,'aaa',23,2000);
I have a question about the syntax for creating and accessing temporary tables.Here is a
related question.
My table
CREATE TABLE IF NOT EXISTS `table1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `table1`
--
INSERT INTO `table1` (`id`, `name`, `address`) VALUES
(1, 'andrew', '5 road'),
(2, 'bob', '6 street');
I am running this query.
CREATE TEMPORARY TABLE temptable SELECT id, name, address
FROM table1
SELECT id, name, address
FROM temptable
And tried this one
CREATE TEMPORARY TABLE temptable SELECT id, name, address
FROM table1
DESCRIBE temptable
Creating the temp table works, but then when I try to get info out of the temp table I get a message saying I need to check my sql syntax.
thanks
andrew
I left out the ';' after each statement. My query should have looked like this
CREATE TEMPORARY TABLE temptable SELECT id, name, address
FROM table1;
SELECT id, name, address
FROM temptable;
Details are important in programming and so is stackoverflow