INSERT/INNER JOIN MYSQL - mysql

I am attempting to insert into the table 'refunds' but I need to reference another table 'transactions' date created. Both tables share the transactionId value. I want to insert into the 'refunds' table if the date created is < 48 hours old. So far I have this insert statement, but cannot get it to work with any sort of join.
INSERT IGNORE INTO refunds
SET
transactionId = ?,
refundAmount = ?

You can do an INSERT/SELECT, something like:
INSERT INTO refunds(transactionId, <col2>, ...)
SELECT transactionId, <col2>, ...
FROM transactions
WHERE date_col > DATE_SUB(CURRENT_DATE, INTERVAL 2 DAY)
This will let you INSERT your refund table based on rows from the transactions table.

Related

Is there a way to INSERT values into one table, then UPDATE values in another table? mySQL

I'm trying to Insert Values into table A, then Update a value in table B in a single stored procedure.
UPDATE Devices
SET Devices.Available = 1
WHERE Devices.DeviceID = DeviceID;
INSERT INTO Withdrawals(Withdrawals.DeviceID,
Withdrawals.StudentID,
Withdrawals.WithdrawalDate,
Withdrawals.Deadline)
VALUES(DeviceID,
StudentID,
CURRENT_DATE,
DATE_ADD(CURRENT_DATE, INTERVAL 7 DAY));
Each query works when executed individually. I've researched how to do this and believe its the right way but for some reason its not executing?

Updating a table after Inserting into another MySQL

I have two tables i am trying to run a query on Table1 Table2
I run a SELECT query on Table1 to return all rows that match a specific date.
I then insert all the returned rows into Table2.
I then want to UPDATE Table1 timestamp after the INSERT
The problem I am having is with the UPDATE part.
Here is what I have:
INSERT INTO Invoices(...)
UPDATE SiteInvoice SET LastInvoiceDate = CURDATE()
SELECT ... FROM SiteInvoice
WHERE lastinvoicedate IS NOT Null AND LastInvoiceDate> CURDATE() - INTERVAL InvoiceFreq WEEK
As pointed out by juergen d, I can not update and insert at the same time. I have added a trigger to the invoice table to update after insert

MySQL:Fill temporary table

I have a table Table1 .For more [details]
I am trying to do a couple of things :
- Get table T2 which have the same fields
- T2 contains rows from Table1 on responding on the following conditions :
- If the difference between the start date and end date for two different rows and for the same id is less than 3 so end date gets the value of the start date else this row will be inserted in T2
I tried to implement it
CREATE TEMPORARY TABLE tempabsences LIKE absences;
INSERT INTO tempabsences(id ,utilisateurs_id,date_debut,tempabsences.date_fin,type,statut)
SELECT absences.utilisateurs_id ,absences.utilisateurs_id,absences.date_debut,absences.date_fin,absences.type,absences.statut
FROM absences
ORDER BY absences.date_debut ASC, absences.utilisateurs_id ASC
ON DUPLICATE KEY UPDATE tempabsences.date_fin=IF(abs(DATEDIFF(tempabsences.date_fin,absences.date_debut)<=3) ,absences.date_fin,tempabsences.date_fin),
tempabsences.date_debut=IF(abs(DATEDIFF(tempabsences.date_fin,absences.date_debut)<=3) ,tempabsences.date_debut,absences.date_debut),
tempabsences.utilisateurs_id=absences.utilisateurs_id ,
tempabsences.id=IF(abs(DATEDIFF(tempabsences.date_fin,absences.date_debut)<=3),tempabsences.id,(select MAX(absences.utilisateurs_id)from absences )+absences.id )
The query don't respond on conditions , it update the row and don't insert it .

2 Dates from the same column in one SQL query

I'm trying to work out an average between of time between two dates in the same field.
Basically i've got a transaction date and an id for each transaction and a customer id for each transaction.
I need to get the time between the first transaction and the second transaction. I dont mind working out the average between the two in excel but I dont know how to pull two dates from the same field.
transaction.created_at of the first transaction minus transaction.created_at of the second transaction for each and every customer in the database. I can pull the date of a transaction like
select
customer.id,
transaction.created_at
count(transaction.id)
from transaction
having count(transaction.id) = 2
Thanks
Not sure if this will always be Having count(*) = 2? If so, I think you could just use min and max, no?
/*
create table dbo.Example (tran_id int,created_at datetime,cust_id int)
insert dbo.example values (1,'10/1/2012',900)
insert dbo.example values (2,'10/2/2012',901)
insert dbo.example values (3,'10/18/2012',590)
insert dbo.example values (4,'10/10/2012',676)
insert dbo.example values (5,'10/11/2012',123)
insert dbo.example values (6,'10/17/2012',456)
insert dbo.example values (7,'10/9/2012',901)
insert dbo.example values (8,'10/30/2012',900)
insert dbo.example values (9,'10/4/2012',456)
insert dbo.example values (10,'10/17/2012',676)
*/
select
cust_id,
max([created_at]) as [Last Date],
min([created_at]) as [First Date],
datediff(hh,min([created_at]) ,max([created_at])) as [Hours diff]
from example
group by cust_id
having count(*) = 2
order by cust_id
Try the following to retrieve particular customer transactions count:
Select
Customer.id,
count(transaction.id)
from transaction
where Customer.id = '10'
Here 10 specifies the customer id that has been searched by you. You have to pass this customer id as parameter in your created SP.

SQL Insert into table only if record doesn't exist [duplicate]

This question already has answers here:
Check if a row exists, otherwise insert
(12 answers)
MySQL Conditional Insert
(13 answers)
Closed 9 years ago.
I want to run a set of queries to insert some data into an SQL table but only if the record satisfying certain criteria are met. The table has 4 fields: id (primary), fund_id, date and price
I have 3 fields in the query: fund_id, date and price.
So my query would go something like this:
INSERT INTO funds (fund_id, date, price)
VALUES (23, '2013-02-12', 22.43)
WHERE NOT EXISTS (
SELECT *
FROM funds
WHERE fund_id = 23
AND date = '2013-02-12'
);
So I only want to insert the data if a record matching the fund_id and date does not already exist. If the above is correct it strikes me as quite an inefficient way of achieving this as an additional select statement must be run each time.
Is there a better way of achieving the above?
Edit: For clarification neither fund_id nor date are unique fields; records sharing the same fund_id or date will exist but no record should have both the same fund_id and date as another.
This might be a simple solution to achieve this:
INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
FROM dual
WHERE NOT EXISTS (SELECT 1
FROM funds
WHERE ID = 23
AND date = DATE('2013-02-12'));
p.s. alternatively (if ID a primary key):
INSERT INTO funds (ID, date, price)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need
see this Fiddle.
Although the answer I originally marked as chosen is correct and achieves what I asked there is a better way of doing this (which others acknowledged but didn't go into). A composite unique index should be created on the table consisting of fund_id and date.
ALTER TABLE funds ADD UNIQUE KEY `fund_date` (`fund_id`, `date`);
Then when inserting a record add the condition when a conflict is encountered:
INSERT INTO funds (`fund_id`, `date`, `price`)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE `price` = `price`; --this keeps the price what it was (no change to the table) or:
INSERT INTO funds (`fund_id`, `date`, `price`)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE `price` = 22.5; --this updates the price to the new value
This will provide much better performance to a sub-query and the structure of the table is superior. It comes with the caveat that you can't have NULL values in your unique key columns as they are still treated as values by MySQL.
Assuming you cannot modify DDL (to create a unique constraint) or are limited to only being able to write DML then check for a null on filtered result of your values against the whole table
FIDDLE
insert into funds (ID, date, price)
select
T.*
from
(select 23 ID, '2013-02-12' date, 22.43 price) T
left join
funds on funds.ID = T.ID and funds.date = T.date
where
funds.ID is null