I have three columns PRODUCTID, PRODUCTNAME, PRODUCTCODE within a table.
I wish to insert a new product creating the PRODUCTID from the other columns
How do I take the first two letters of PRODUCTNAME and the last four numbers of PRODUCTCODE and populate them into PRODUCTID?
I do not want a product to be duplicated within the table and if attempted I want the table to remain unchanged. The default PRODUCTID is DEFAULT.
I have so far got:
INSERT INTO `v1_products` (`PRODUCTNAME`, `PRODUCTNUMBER`) VALUES ("EXAMPLE", "EXAMPLE4444");
UPDATE `v1_products`
SET `PRODUCTID`=(SELECT CONCAT(
(SELECT LEFT(`PRODUCTNAME`,2)) , (SELECT RIGHT(`PRODUCTNUMBER`,4))))
WHERE `PRODUCTID`= "DEFALT" AND `PRODUCTID`!=`PRODUCTID`
LIMIT 1
First off I would reccomend setting the PRODUCTID column to be unique. This will prevent any products from having the same values. If your default PRODUCTID is "default" then you may need to do this after updating the ids.
Your UPDATE statement is fine except from the WHERE clause:
WHERE `PRODUCTID`= "DEFALT" AND `PRODUCTID`!=`PRODUCTID`
There's a typo in "DEFAULT" and
`PRODUCTID`!=`PRODUCTID`
Will never be true.
WHERE `PRODUCTID`= "DEFAULT"
Should be enough.
The above will fix existing products with incorrect ids. Now you should change your insert so that PRODUCTID is set correctly for each new product. You can do this by simply adding the CONCAT you used in the update statement:
INSERT INTO `v1_products` (`PRODUCTID`, `PRODUCTNAME`, `PRODUCTNUMBER`)
VALUES (
CONCAT(
LEFT("EXAMPLE",2),
RIGHT("EXAMPLE4444",4)),
"EXAMPLE",
"EXAMPLE4444");
From the discussion in the comments an example of only setting the columns values once:
INSERT INTO v1_products (PRODUCTNAME, PRODUCTNUMBER,PRODUCTID)
VALUES (
"EXAMPLE",
"EXAMPLE4444",
CONCAT( LEFT(PRODUCTNAME,2), RIGHT(PRODUCTNUMBER,4)));
Related
I need to create an identical copy of many records in a table. The table has a PK id, which of course will be different, in the freshly-copied records.
For example, let's say i have a scrum_card table, with the following non-unique columns: name, description, board_id
I have a dynamic array of id's of records, which i wish to duplicate: [34,56,32,3445,...]
How do i tell MYSQL, to fetch the data from all those records, and make a batch-insert of those same records?
In "human" syntax it would look something like this: "Select all columns(besides id) from scrum_card where the id's are [array of id's], then duplicate each found record".
Use INSERT INTO ... SELECT... and in the list of columns do not include the id:
insert into scrum_card(name, description, board_id)
select name, description, board_id
from scrum_card
where id in (34,56,32,3445,...)
You can use INSERT using a SELECT result set as the source, instead of a set of literal row tuples with VALUES(...).
INSERT INTO new_table (id, col1, col2, col3...)
SELECT NULL, col1, col2, col3...
FROM old_table
WHERE id IN (34,56,32,3445,...)
Using NULL in place of the id column in the SELECT will return NULL for each row, which will cause new_table to generate a new id value.
But SQL does not have any way to do a wildcard like "all columns except id," besides you typing the column names in.
I'm trying to update an empty table notes, with values that come from a column in another table deals:
UPDATE notes
SET notes.content = (
SELECT deals.memo
FROM deals
WHERE deals.id = notes.deal_id
);
this runs with no error but no notes get updated although there are loads of values in memo.
There's no values at all in notes. Can this be the problem?
Perhaps you want to insert rows into notes:
INSERT INTO notes (deal_id, content)
SELECT d.id, d.ememo
FROM deals;
This will add rows into notes with values from the rows in deals.
I'm new to SQL, so I think this will have a simple answer, but I'm having trouble tracking down a comparable example via google.
I have two tables in a SQL database with similar values, but a different number of columns with different column names. I need to migrate the the values from the first database (catalog_product_entity_tier_price) into the second database (mb_tierprices_list) and then fill in the gaps with a default value.
This is where I'm up to:
INSERT INTO catalog_product_entity_tier_price (entity_id, website_id, qty, value)
SELECT entity_id, website_id, price_qty, percent
FROM mb_tierprices_list;
But I also need to handle three more columns in catalog_product_entity_tier_price with default values:
value_id (this is set to AUTO_INCREMENT, so nothing to do there)
all_groups = 1
customer_group_id = 0
Should I split this into two queries and just do a second one like so:
INSERT INTO catalog_product_entity_tier_price (all_groups, customer_group_id)
VALUES (1, 0);
Is there a preferred way to accomplish this?
Just put the default values in your select like this:
INSERT INTO catalog_product_entity_tier_price (entity_id, website_id, qty, value, all_groups, customer_group_id)
SELECT entity_id, website_id, price_qty, percent, 1, 0
FROM mb_tierprices_list;
i got the following mysql query..I have tried many different format but cant seem to get this to work.
I got two tables. table mic.temp has three columns while table products has quite a few.
I need to update values into table products from table mic.temp. The matching column is model number.
i have written the following query but it updates all the field.I only need to update the values found in temp table and also auto increment the product table.if a value is not found then insert it.I don't mind if non existent values in temp table are entered as null.
mysql_query('INSERT INTO products(products_id, products_quantity, products_model, products_ean, products_image, products_price, products_date_added, products_last_modified, products_date_available, products_weight, products_status, products_tax_class_id, manufacturers_id, products_ordered, products_last_import, icecat_prodid, vendors_id, products_availability)
SELECT model, stock, price
FROM mic_temp
ON DUPLICATE KEY UPDATE set
products.products_quantity = mic_temp.stock,
products.products_price= mic_temp.price');
Check this:
Update products join mic_temp on products.modelnumber=mic_temp.modelnumber set
products.product_quantity=mic_temp.stock, products.product_price=mic_temp.price;
Specify all columns of mic_temp which you want to insert or update in products table under
set statement.
I have this Statement:
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1));
I'm trying to insert a value copy the same data of item_costprice, but show me the error:
Error Code: 1136. Column count doesn't match value count at row 1
How i can solve this?
Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
SELECT
/* Literal number values with column aliases */
1 AS item_code,
2 AS invoice_code,
item_costprice
FROM qa_items
WHERE item_code = 1;
Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice, but in a normal SELECT you'll need the aliases to access the columns returned.
You can just simply e.g.
INSERT INTO modulesToSections (fk_moduleId, fk_sectionId, `order`) VALUES
((SELECT id FROM modules WHERE title="Top bar"),0,-100);
I was disappointed at the "all or nothing" answers. I needed (again) to INSERT some data and SELECT an id from an existing table.
INSERT INTO table1 (id_table2, name) VALUES ((SELECT id FROM table2 LIMIT 1), 'Example');
The sub-select on an INSERT query should use parenthesis in addition to the comma as deliminators.
For those having trouble with using a SELECT within an INSERT I recommend testing your SELECT independently first and ensuring that the correct number of columns match for both queries.
Your insert statement contains too many columns on the left-hand side or not enough columns on the right hand side. The part before the VALUES has 7 columns listed, but the second part after VALUES only has 3 columns returned: 1, 2, then the sub-query only returns 1 column.
EDIT: Well, it did before someone modified the query....
As a sidenote to the good answer of Michael Berkowski:
You can also dynamically add fields (or have them prepared if you're working with php skripts) like so:
INSERT INTO table_a(col1, col2, col3)
SELECT
col1,
col2,
CURRENT_TIMESTAMP()
FROM table_B
WHERE b.col1 = a.col1;
If you need to transfer without adding new data, you can use NULL as a placeholder.
If you have multiple string values you want to add, you can put them into a temporary table and then cross join it with the value you want.
-- Create temp table
CREATE TEMPORARY TABLE NewStrings (
NewString VARCHAR(50)
);
-- Populate temp table
INSERT INTO NewStrings (NewString) VALUES ('Hello'), ('World'), ('Hi');
-- Insert desired rows into permanent table
INSERT INTO PermanentTable (OtherID, NewString)
WITH OtherSelect AS (
SELECT OtherID AS OtherID FROM OtherTable WHERE OtherName = 'Other Name'
)
SELECT os.OtherID, ns.NewString
FROM OtherSelect os, NewStrings ns;
This way, you only have to define the strings in one place, and you only have to do the query in one place. If you used subqueries like I initially did and like Elendurwen and John suggest, you have to type the subquery into every row. But using temporary tables and a CTE in this way, you can write the query only once.