copy all rows with matching field value - php

I would like to copy all mysql rows with a matching field value into a new row and change one field.
So I have a mysql table with the following fields
`lessonplan`, `group`, `category`, `sort_id`, `item`
So I want to copy all rows that have lessonplan=10 and set change the value of lessonplan to 11 for all new rows. Lesson plan is not an auto increment field.
What is best practice for a scenario like this one?

INSERT INTO tableName( lessonplan, `group`, category, sort_id, item )
SELECT 11, `group`, category, sort_id, item
FROM tableName
WHERE lessonplan = 10

Related

How can I UPDATE a column in a record when that information is the result of a GROUP CONCAT in the same table?

I cannot determine if this should be something nested or a JOIN.
Each record has three values from the column value across from their name in the column variable.
I have a successful GROUP CONCAT that combines them into a single text string.
BUT, I need to UPDATE/INSERT the concat value into another variable=>value pair.
Such as this. I want each person to have "cityStateZip" in the value for `cust_abc'.
I believe it's "INSERT" and not update since none of the records have anything in cust_abc yet. But, I'm not quite sure if it shouldn't be UPDATE.
id_member
variable
value
1234
cust_abc
"should show citystatezip"
1234
cust_a
city
1234
cust_b
state
1234
cust_c
zip
I can't get past the error of having the target table being the same in the SELECT FROM.
I was attempting things like:
INSERT INTO smgqg_themes.value (my group concat) WHEN `variable` = "cust_abc"
This is the group concat that works fine to make the string:
SELECT GROUP_CONCAT
( `value`
order by case variable
when 'cust_a' then 1
when 'cust_b' then 2 else 3 end
SEPARATOR '')
output
FROM smfqg_themes
WHERE `id_member` IN (1234, 1235, 1236, etc)
AND `variable` IN ('cust_a', 'cust_b', 'cust_c')
You can INSERT into a the same table you SELECT from in the same SQL statement. I do this all the time.
The syntax is:
INSERT INTO <tablename> (<columns...>)
SELECT ...;
The SELECT must return the same columns that you name in the INSERT clause, in the same order.
If you want an existing row to be updated, but still insert a row if one is missing with the 'cust_abc' varible, then you can use INSERT...ON DUPLICATE KEY UPDATE:
INSERT INTO smgqg_themes (id_member, variable, value)
SELECT id_member, 'cust_abc',
GROUP_CONCAT(`value`
ORDER BY CASE variable
WHEN 'cust_a' THEN 1
WHEN 'cust_b' THEN 2 ELSE 3 END
SEPARATOR '') as v
FROM smgqg_themes
WHERE `id_member` IN (1234, 1235, 1236)
AND `variable` IN ('cust_a', 'cust_b', 'cust_c')
GROUP BY `id_member`
ON DUPLICATE KEY UPDATE value = VALUES(value);
Demo: https://dbfiddle.uk/OPJQ1ZXF

how to insert a new record in a table that has foreign key attributes in mysql

What is wrong in this statement since customers table has only one record
INSERT INTO CART (Cartid,custid,Pid)
VALUES ('2',SELECT(custid from CUSTOMERS), SELECT (Pid from Products where Pname ='shirts'))
Make sure that the cart table id is primary key and auto_increment. Get the customer id and store in a variable. You can try something similar like this
INSERT INTO CART (Cartid,custid,Pid) VALUES ('', SELECT custid from CUSTOMERS WHERE custid = '$customer_id'),(SELECT Pid FROM Products WHERE Pname = 'shirts' LIMIT 1));
The correct syntax is:
INSERT INTO CART (Cartid, custid, Pid)
VALUES (2,
(SELECT custid FROM CUSTOMERS LIMIT 1),
(SELECT Pid FROM Products WHERE Pname = 'shirts' LIMIT 1)
);
Your parentheses are in the wrong place.
Notes:
I added the LIMIT just to enforce that one row is returned.
I removed the single quotes around '2', because ids are usually number.
You probably should not be inserting the id; it should be an auto-increment column.

SQL Statement INSERT, on duplicate columns UPDATE

I have an SQL Table that contains a list of items that users can have linked to their profile. The SQL table looks something like this:
Item_Activity_ID Item_ID User_ID Status Date-Added
1 1 1 1 2015-06-08
2 2 2 1 2015-06-08
3 1 1 0 2015-06-09
The entry shows that someone with the user with id of 1 added item id 1 twice, and the only thing that was changed was the date and status. I want to make it so that when given an INSERT statement such as:
INSERT INTO items (Item_ID, User_ID, Status, Date_Added) VALUES ('$x', '$y', 1, CURDATE()) IF EXISTS SOME Item_ID = $x AND User_ID = $y UPDATE items SET Status = 1, Date_Added = CURDATE() WHERE Item_ID = $x AND User_ID = $y
Item_Activity_ID is an auto_incremented primary key index. How can I accomplish this in one query? Two users can have the same item, but where should never be repeat entries of the same user id and item id.
First, create a unique index for Item_ID, UserID combination,
Then, use the INSERT ... ON DUPLICATE KEY UPDATE statement:
INSERT INTO items (Item_ID, User_ID, Status, Date_Added)
VALUES ('$x', '$y', 1, CURDATE())
ON DUPLICATE KEY UPDATE Status = VALUES(Status), Date_Added = VALUES(Date_Added))
P.S. make sure to sanitize $x and $y to prevent SQL injections!
I would start by adding a unique key index:
ALTER TABLE items
ADD CONSTRAINT uc_UserItem UNIQUE (Item_ID,User_ID);
Then, you can just modify your insert query:
INSERT INTO items (Item_ID, User_ID, Status, Date_Added) VALUES ('$x', '$y', 1, CURDATE()) ON DUPLICATE KEY UPDATE Status=VALUES(1), Date_Added=VALUES(CURDATE());
Try to perform the update first supposing that the user and item already exist. Then check if this update affects any rows (using ##rowcount, in SQL Server).
If not then perform an insert.
Don't forget to put the above two statements in a transaction... ;)
Normal way would be to set a composite constraint at the db level. If you are using mysql and phpmyadmin you do this in the table structure view.
Check both fields (I guess 'user_id' and 'item_id') and click the 'unique' button.
After that is set you can just append
ON DUPLICATE KEY UPDATE status =1, date_added=CURDATE().
It will update the row that violated the constraint you created

INSERT on update. Compound Key

I have a question on This MySQL statement.
I got this from this post
However, I am not sure how to structure the query when I have the table like this.
TableA
--------
id ==> Auto Increment field
question_id
form_id
member_id
event_id
admin_id
desc
is_cand_field
c_field_id
In this, question_id, form_id, memmber_id, event_id, admin_id can be same. desc, is_cand_field, c_field_id can change. When inserting, I want to check if this combination exists. If exists, I want to update the last 3 fields. If not, I want to insert a record.
Is this possible with the above referred query. Its not clear from the page.
Add unique key on combination of these fields:
ALTER TABLE `tablea` ADD UNIQUE INDEX `compound_key` (`question_id`, `form_id`, `member_id`, `event_id`, `admin_id`);
Insert values and add update section:
INSERT INTO tablea (`question_id`, `form_id`, `member_id`, `event_id`, `admin_id`, `desc`, `is_cand_field`, `c_field_id`)
VALUES (1, 2, 3, 4, 5, 1, 0, 1)
ON DUPLICATE KEY UPDATE `desc` = VALUES(`desc`), is_cand_field = VALUES(`is_cand_field`), c_field_id = VALUES(`c_field_id`)
You can add multiple rows in the ON DUPLICATE KEY UPDATE section.
INSERT INTO TableA (form_id, member_id, event_id, admin_id, desc, is_cand_field, c_field_id)
VALUES (2, 3, 4, 5, 'b', 0, 1)
ON DUPLICATE KEY UPDATE desc='a', is_cand_field=1, c_field_id=2

SQL command to copy selected content from selected rows into other rows?

Any idea how to copy: name, content from rows where language_id = 1 to rows where language_id = 2?
How should SQL command look like?
I want to achive:
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html is what you need to do
assuming it is the productid that you want to update from lang1 to lang 2
update a set
a.name = b.name,
a.content = b.content
from tablea a
join tablea b on a.productid = b.productid
where a.language_id = 2
and b.language_id = 1
ofcourse this will do it for every row in the table so if you want to restrict it then make sure to restrict it by the productids
Did you mean copying all language_id=1 rows to language_id=2 ones?
My knowledge of MySQL syntax is very poor, so I dare not give you all the codez, but at least you may find the following approach useful:
Create a temp table with the structure like this:
product_id int,
name (varchar?)
content (varchar?)
That is, include product_id and all the columns you need to copy.
Populate the temp table with the language_id=1 data. Probably like this:
INSERT INTO temp_table
SELECT product_id, name, content
FROM orig_table
WHERE language_id = 1
Update those rows in the original table where language_id=2 with the corresponding data in the temp table. It may look like this:
UPDATE orig_table
SET
name = temp_table.name,
content = temp_table.content
FROM temp_table
WHERE orig_table.product_id = temp_table.product_id
AND orig_table.language_id = 2
Insert the rows from the temp table into the original table, where the products don't have language_id=2. Something like this:
INSERT INTO orig_table (product_id, language_id, name, content)
SELECT product_id, 2, name, content
FROM temp_table
WHERE NOT EXISTS (
SELECT 1 FROM orig_table
WHERE product_id = temp_table.product.id
AND language_id = 2
)
If you didn't mean to change the already existing language_id=2 data, then step #3 should be omitted and you might further want to modify step #2 in such a way that it selected language_id=1 data only for the products lacking language_id=2.

Categories