I have two tables.
basically i want to insert an id and a string into a table
However, id is a foreign key to another table in which customerId is the primary key
Furthermore my parent table has name
What i have, is name and the stringthat i get from a web ui. However, since i dont have the id that match the customerid of name in the parent table, i don't know how to insert it.
i got this so far, which by the way is my silly attempt to work my human logic around this issue:
INSERT INTO `PostDb`(`Offer`)
VALUES ("String") AND PostDb.id
WHERE CustomerDb.id = PostDb.id AND CustomerDb.name = "MyNameThatIHave"
What would work though. is that i do the following:
SELECT PostDb.id
FROM `PostDb` JOIN CustomerDb
WHERE `CustomerId` = CustomerDb.id AND CustomerDb.name = "MyNameThatIHave"
And then use the id that i get in a new insert command like this:
INSERT INTO `PostDb`(`CustomerId`, `Offer`)
VALUES ("THE ID I GOT BEFORE","STRING")
Basically i want to achieve in ONE query, what the two before stated queries does
You can use SELECT to get values for insert:
INSERT INTO `PostDb`(`Offer`, customerid)
SELECT 'Whatever', id FROM customerdb
WHERE name = 'MyNameThatIHave'
Have you tried LAST_INSERT_ID() function which gives you the last inserted ID PK provided that ID is an auto_increment column.
Once you get that, then you can insert in your child table in your FK column along with the rest attributes.
In that case, use a INSERT INTO .. SELECT FROM construct like
INSERT INTO `PostDb`(`CustomerId`, `Offer`)
SELECT PostDb.`CustomerId`, 'Some Value'
FROM `PostDb` JOIN CustomerDb
ON `PostDb`.`CustomerId` = CustomerDb.id
WHERE CustomerDb.name = "MyNameThatIHave";
Related
I have CSV files and I need to do something like this before inserting data in my table:
table fields
id = primary id and auto-increment
house_no
city_code
prv_code
cty_code
if (house_no,city_code,prv_code,cty_code) exists = ignore insert
else if (house_no,city_code,prv_code,cty_code) is null = ignore insert
else (house_no,city_code,prv_code,cty_code) !exist = insert
My original code just re-inserts the same values because the primary key id is just creating a new id for it and as a result I have duplicates.
I need to do this to avoid duplicates. I tried INSERT IGNORE and REPLACE but I need a unique key and all fields may have a value which is the same (like they may have different house_no but the same prv_code or cty_code or something like that). I just want to check if the record exist before I insert it.
You can create a unique key over more than one column. In your case you need an unique key containing of the four columns house_no, city_code, prv_code and cty_code.
In your case:
ALTER TABLE fields
ADD CONSTRAINT uc_fieldsUnique UNIQUE (house_no,city_code,prv_code, cty_code);
Load data from CSV-file into second table, and then use INSERT like this to add rows -
INSERT INTO t1(id, house_no, city_code, prv_code, cty_code)
SELECT NULL, t2.house_no, t2.city_code, t2.prv_code, t2.cty_code FROM t2
LEFT JOIN t1 ON t1.house_no = t2.house_no AND t1.city_code = t2.city_code AND t1.prv_code = t2.prv_code AND t1.cty_code = t2.cty_code
WHERE t1.id IS NULL
(rename table names)
I want to insert a value into a table. However that value comes from that table too. And I want to check if there is a duplicate key on that table. Since this value come from that table too, the query says that a column name is ambiguous.
$result2 = "INSERT INTO estock_saldo
(items, customer_id, quantity , reference_no, size)
SELECT
items, '".$member_id."', '".$quantity[$i]."', reference_no, size
FROM
estock_saldo
WHERE id in ({$order_id[$i]})
ON DUPLICATE KEY
UPDATE estock_saldo.quantity = estock_saldo.quantity - '".$quantity[$i]."'";
$res2 = $mysqli->query($result2);
if(!$res2){ printf("Errormessage 2: %s\n", $mysqli->error); die(); }
The ambiguous come from estock_saldo.quantity. I have tried to alias the column name. However you can't do that in insert table.
Problem persist in the below shown code snippet. You can't use column alias in INSERT statement.
INSERT INTO estock_saldo
(items, customer_id, quantity AS asquan
<-- HERE
What you are trying will always have a duplicate entry, since you are inserting the same record again. Instead of INSERT statement, you actually meant to do a UPDATE like
UPDATE estock_saldo SET
quantity = quantity - '".$quantity[$i]."'"
WHERE id in ({$order_id[$i]});
I need to create a query to insert some records, the record must be unique. If it exists I need the recorded ID else if it doesnt exist I want insert it and get the new ID. I wrote that query but it doesnt work.
SELECT id FROM tags WHERE slug = 'category_x'
WHERE NO EXISTS (INSERT INTO tags('name', 'slug') VALUES('Category X','category_x'));
It's called UPSERT (i.e. UPdate or inSERT).
INSERT INTO tags
('name', 'slug')
VALUES('Category X','category_x')
ON DUPLICATE KEY UPDATE
'slug' = 'category_x'
MySql Reference: 13.2.5.3. INSERT ... ON DUPLICATE KEY UPDATE Syntax
Try something like...
IF (NOT EXISTS (SELECT id FROM tags WHERE slug = 'category_x'))
BEGIN
INSERT INTO tags('name', 'slug') VALUES('Category X','category_x');
END
ELSE
BEGIN
SELECT id FROM tags WHERE slug = 'category_x'
END
But you can leave the ELSE part and SELECT the id, this way the query will always return the id, irrespective of the insert...
MySQL has nice REPLACE. It is easy to use and remember it's syntax as same as INSERT.
in you case, just run following query.
REPLACE INTO tags('name', 'slug') VALUES('Category X','category_x')
It acts like INSERT when no unique constraint violation. If duplicated value found on PK or UNIQUE key, then other columns will be UPDATED with given values. It is done by DELETE duplicated record and INSERT new record.
I have a simple table like this
CREATE TABLE authid(
id INT NOT NULL AUTO_INCREMENT,
authid VARCHAR(128) NOT NULL UNIQUE,
PRIMARY KEY(id)
);
Now if I insert a value with
INSERT INTO authid(authid) VALUES('test');
It will work fine and return the inserted id the first time, but if I do it again when the authid already exists (notice that we have authid marked as UNIQUE) it will return an error.
Is there a way achieve this this in one SQL statement: Insert it, get the id and if it already exists, still get the id.
Take a look at this: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If you're using MySQL 5.0 or higher you can use the "INSERT ... ON DUPLICATE KEY UPDATE" syntax. You may be able to combine that with LAST_INSERT_ID() (I'm not positive about that)
So:
insert into authid (authid) values ('test') on duplicate key update id=LAST_INSERT_ID(id), authid='test';
select LAST_INSERT_ID();
Well indeed if you try to insert 2 times the same value in a UNIQUE field, it won't work, that's the point of UNIQUE fields.
If I understand well, you want to know if it's possible whether to use an INSERT or an UPDATE statement depending on the existance of an item or not ? Then you need 2 queries, 1 to test existence, the other to insert new value or update existing one
Insert the value conditionally (i.e. if it doesn't exist). Whether the insert takes place or not, by the end of the statement the result will be the same: the value will be in the table. So, just select the ID of the row that matches that value. Or, speaking in SQL, like this:
INSERT INTO authid (authid)
SELECT 'test'
WHERE NOT EXISTS (
SELECT *
FROM authid
WHERE authid = 'test'
);
SELECT id
FROM authid
WHERE authid = 'test'
;
Alright, i have revised the question to also include what i have so far, and what i want to do. So here goes it:
CREATE ORDER (
product_nat_id int(3) NOT NULL,
name VARCHAR(20),
PRIMARY KEY (product_nate_id)
)
INSERT INTO ORDER(product_nat_id, name) VALUES(1, 'Product 1');
INSERT INTO ORDER(product_nat_id, name) VALUES(2, 'Product 2');
INSERT INTO ORDER(product_nat_id, name) VALUES(3, 'Product 3');
CREATE TABLE INT_PRODUCT (
product_id INTEGER NOT NULL AUTO_INCREMENT,
product_nat_id INTEGER NOT NULL,
title TINYTEXT,
dateCreate TIMESTAMP CURRENT_TIMESTAMP,
CONSTRAINT INT_PRODUCT_PK PRIMARY KEY (product_id),
UNIQUE INT_PRODUCT_NK (product_nat_id));
But what i want is, whenever a record arrives with an updated value but duplicate key, i need to insert it (and not updated), but avoid duplicate constraint based on the difference in time inserted. Hope this makes sense now.
I would suggest the following:
Look up the previous record. I assume you should know what that would be
SELECT Count(*) FROM dim WHERE recordId = '$recordid'
If in step 1 the records returned are larger than 0 then invalidate the 'previous' record:
UPDATE dim SET datevalid = '$datevalue' where recordId = '$recordid' and status = 2
Continuing with step 1 where the ecords return in the check are larger than 0 now do the insert:
INSERT INTO dim (recordId,field1,field2,date,status) VALUES (1,'sad','123123','2013-03-26',1)
If step 1 was false then just do the insert:
INSERT INTO dim (recordId,field1,field2,date,status) VALUES (1,'sad','123123','2013-03-26',1)
I would add a status field just as an extra measure when you need to find records and distinguish between valid or invalid then you do not need to filter between dates. You can then use the status field. Also have a unique auto-increment key for every record even though the data might be the same for a set of valid and invalid records. recordId and unique key will not be the same in this case. You assign the recordId and the system will assign the unique key on the table. status = 1 is valid and status = 2 is invalid.
Hope this helps!
sample code of your post like as:
Insert query syntax looks like this:
INSERT INTO table (primarykeycol,col1,col2)
VALUES (1,2,3) ON DUPLICATE KEY UPDATE col1=0, col2=col2+1
If there is already a row with primarykeycol set to 1 this query is equal to:
UPDATE table SET col1=0, col2=col2+1 WHERE primarykeycol = 1
explanation as:
Ordinarily to achieve the same result you would have to issue an
UPDATE query, then check if there were affected rows and if not
issue an INSERT query.
This way, you can do everything in one step – first try insert and
then update if insert fails.
One situation for which this type of syntax is perfect is when you
work with daily counters. For example, you might have a table with
PostID, Date and Count columns.
Each day you’d have to check if you already created an entry for
that day and if so increase the count column – and this can be
easily substituted with one INSERT … ON DUPLICATE KEY UPDATE query.
Unfortunately there are some caveats. One being that when you have
multiple unique indexes it will act as if you had an OR condition in
WHERE clause of UPDATE query.
This means that multiple rows should be update, but INSERT … ON
DUPLICATE KEY UPDATE will update only one row.
MySQL manual: INSERT ON DUPLICATE KEY UPDATE Syntax