I have two table with column like this:
Table aggthndet (Reference table)
SELECT `aggthndet`.`idaggdet`,
`aggthndet`.`idagg`,
`aggthndet`.`noakun`,
`aggthndet`.`ketdet`,
`aggthndet`.`pagu`,
`aggthndet`.`prosesagg`,
`aggthndet`.`realisasi`,
`aggthndet`.`iu_id_usr`,
`aggthndet`.`iu_wkt`,
`aggthndet`.`iu_stat`FROM `aggthndet`;
Table aggakundet
SELECT `aggakundet`.`id`,
`aggakundet`.`idaggdet`,
`aggakundet`.`ketdetakun`,
`aggakundet`.`volume`,
`aggakundet`.`hrg_satuan`,
`aggakundet`.`iu_id_usr`,
`aggakundet`.`iu_wkt`,
`aggakundet`.`iu_stat`
FROM `aggakundet`;
The tables are mutually related to each other (relationship one-to-many)
i want insert data into table aggakundet, and update column pagu on table aggthndet, pagu column is the sum of the overall jml_total (alias column) of columns that have the same idaggdet.
sample data
table aggthndet
table aggakundet
In your script, you are having the value of idaggdet in $idaggdet.
Once insertion is done, proceed with UPDATE using the values in $idaggdet
You can take the below query as reference,
UPDATE `aggthndet`
SET `pagu` = `pagu`+1
WHERE `idaggdet` = '$idaggdet';
You can append this update statement in $sql itself.
Related
I have 50 columns in the MySQL table. I want to sum all these columns and make a new column into the same table (sum50).
This should be stored permanently into the MySQL table whenever I update or insert new data.
I know how to sum up while performing the query but it does not store into the table permanently.
CREATE TRIGGER `name`
AFTER INSERT ON `table`
FOR EACH ROW
UPDATE `table` SET `table`.`coulms` = `table`.`col1`+.... `table`.`col50`+
I am trying the above trigger, but not working.
Should I have a blank column inserted into the table and perform trigger? Which trigger would be correct?
Instead of the trigger, add a generated column to your table:
alter table tablename add(sum50 int generated always as (col1 + col2 + ...) stored);
See a simplified demo.
I'd like to
UPDATE table SET column = 1 where column = 0;
INSERT (rows i just updated) INTO history_table;
Can I somehow store the ids from a select query, and then use those to UPDATE and subsequently INSERT rows matching those ids into the history table?
INSERT INTO history_table(id)
(SELECT id from table WHERE column = 0);
UPDATE table SET column = 1 where column = 0;
This way you are only getting the ID's that will be updated for the history_table and then you can update them to the correct values.
(I can't comment yet) Is there a specific reason to do it one query?
If not then you might use temporary table to store ids and fetch them for your update and insert using subquery.
I have two tables ,location and locationdata. I want to query data from both the tables using join and to store the result in a new table(locationCreatedNew) which is not already present in the MySQL.Can I do this in MySQL?
SELECT location.id,locationdata.name INTO locationCreatedNew FROM
location RIGHT JOIN locationdata ON
location.id=locationdata.location_location_id;
Your sample code in OP is syntax in SQL Server, the counter part of that in MySQL is something like:
CREATE TABLE locationCreatedNew
SELECT * FROM location RIGHT JOIN locationdata
ON location.id=locationdata.location_location_id;
Referance: CREATE TABLE ... SELECT
For CREATE TABLE ... SELECT, the destination table does not preserve information about whether columns in the selected-from table are generated columns. The SELECT part of the statement cannot assign values to generated columns in the destination table.
Some conversion of data types might occur. For example, the AUTO_INCREMENT attribute is not preserved, and VARCHAR columns can become CHAR columns. Retrained attributes are NULL (or NOT NULL) and, for those columns that have them, CHARACTER SET, COLLATION, COMMENT, and the DEFAULT clause.
When creating a table with CREATE TABLE ... SELECT, make sure to alias any function calls or expressions in the query. If you do not, the CREATE statement might fail or result in undesirable column names.
CREATE TABLE newTbl
SELECT tbl1.clm, COUNT(tbl2.tbl1_id) AS number_of_recs_tbl2
FROM tbl1 LEFT JOIN tbl2 ON tbl1.id = tbl2.tbl1_id
GROUP BY tbl1.id;
NOTE: newTbl is the name of the new table you want to create. You can use SELECT * FROM othertable which is the query that returns the data the table should be created from.
You can also explicitly specify the data type for a column in the created table:
CREATE TABLE foo (a TINYINT NOT NULL) SELECT b+1 AS a FROM bar;
For CREATE TABLE ... SELECT, if IF NOT EXISTS is given and the target table exists, nothing is inserted into the destination table, and the statement is not logged.
To ensure that the binary log can be used to re-create the original tables, MySQL does not permit concurrent inserts during CREATE TABLE ... SELECT.
You cannot use FOR UPDATE as part of the SELECT in a statement such as CREATE TABLE new_table SELECT ... FROM old_table .... If you attempt to do so, the statement fails.
Please check it for more. Hope this help you.
Use Query like below.
create table new_tbl as
select col1, col2, col3 from old_tbl t1, old_tbl t2
where condition;
Consider two tables that have timestamp and data columns. I need to construct an SQL that does the following:
Insert data (unique timestamp and data column) in one table if timestamp value is not present in the table ("insert my data in table 1 for timestamp="12:00 1999-01-01" only if that timestamp is not present in table 1...)
Otherwise, insert very same data in different table without any checks, and overwrite if necessary (... otherwise insert same set of fields in table 2).
How I could possibly achieve this on SQL? I could do it using a client but this is way slower. I use MySQL
Run a query for your 2nd bullet first. i.e. insert data into table 2 if it is present in table 1
insert into table2 (data, timestamp)
select 'myData', '12:00 1999-01-01'
from table1
where exists (
select 1 from table1
where timestamp = '12:00 1999-01-01'
)
limit 1
Then run your the query for your 1st bullet i.e. insert into table1 only if the data doesn't already exist
insert into table1 (data, timestamp)
select 'myData', '12:00 1999-01-01'
from table1
where not exists (
select 1 from table1
where timestamp = '12:00 1999-01-01'
)
limit 1
Running both these queries will always only insert 1 row into 1 table because if the row exists in table1, the not exists condition of the 2nd query will be false and if it doesn't exist in table1, then the exists condition of the 1st query will be false.
You may want to consider creating a unique constraint on table1 to automatically prevent duplicates so you can use insert ignore for your inserts into table1
alter table table1 add constraint myIndex (timestamp);
insert ignore into table1 (data,timestamp) values ('myData','12:00 1999-01-01');
A regural INSERT statement can insert records into one table only. You have 2 options:
Code the logic within the application
Create a stored procedure within mysql and code the application logic there
No matter which route you choose, I would
Add a unique index on the timestamp column in both tables.
Attempt to insert the data into the 1st table. If the insert succeeds, everything is OK. If the timestamp exists, then you will get an error (or a warning depending on mysql confioguration). Your solution handles the error (in mysql see DECLARE ... HANDLER ...).
Insert the data into the 2nd table using INSERT INTO ... ON DUPLICATE KEY UPDATE ... statement, which will insert the data if the timestamp does not exists, or updates the record if it does.
I added a new column to an existing table(columns acadid,orgid,childid) and now I want to insert values for it.
alter table table1 add new_parent int
insert into table (new_parent) select parent from (select parent
from table2 o inner join table1 ou
on ou.orgid=o.orgunitid) np
Here:
select parent
from table2 o inner join table1 ou
on ou.orgid=o.orgunitid
this query gives me multiple values(multiple rows) for the new parent column.
But the above code gives me the following error:
Cannot insert the value NULL into column 'acadid', table
'tempdb.dbo.table1______________________________________________________________000000014F2B'; column does not allow nulls. INSERT fails. The statement has been
terminated.
How can I fix it?
The reason why you have this error message is that you added a new column to your table1 table with the alter table statement, but instead of updating the value of this column for existing rows, you are adding new rows with only this column filled with an insert statement, and there may be a constraint (a primary key constraint?) on another column that does not allow nulls.
Instead of that, you probably want to update the value of this new column for the existing rows with an update like:
update table1
set table1.new_parent = table2.parent
from table1 inner join table2 on table2.orgid=table1.orgunitid