I have the tables:
Credit_account
==============
Acid int (PK)(AI)
Customer Id(Foreign Key ref Customer Table)
Credit Account char(15);
I want to insert record as
1 2 1-2
2 3 2-3
3 1 1-3
Is there any specific reason why you must use a select statement? Then there is some missing information.
If you have to use a select statement, it could be because the data from this table is from a JOIN. Else, you do not need multiple SELECT statements. An INSERT statement is sufficient.
Related
I realize similar questions have been asked before, but I can't seem to find a solution that fits this particular scenario.
I would like to insert multiple rows of data into a mariaDB table where the data must be unique (primary key excluded).
Sample table:
enrollmentsID
classID
userID
1
1
2
2
1
3
3
1
4
4
2
2
5
2
7
So if I want to insert a number of rows, I don't want to duplicate what's already present.
The general idea is something like:
INSERT INTO `enrollments` (`enrollmentsID`, `classID`, `userID`)
VALUES (NULL,1,2),(NULL,1,3),(NULL,1,4),(NULL,1,5)
WHERE NOT EXISTS (
SELECT `enrollments`.`classID`, `enrollments`.`userID`
FROM `enrollments`)
Here, userID 5 would insert but userID 3 and userID 4 would be ignored.
Unfortunately, the WHERE is causing issues... Thanks for any help provided.
As P.Salmon mentioned in the comments, a UNIQUE index on the two columns is likely what you need. The index needs to be on both columns, not a UNIQUE index for each column.
ALTER TABLE enrollments
ADD UNIQUE INDEX (`classID`,`userID`)
From there you can do INSERT INGORE INTO instead of INSERT INTO and that will only insert the unique entries.
Let's say I have these two tables. Where I insert employees to employee table coming from the staging table.
staging table:
id
employee_id
name
1
12
Paul
2
13
Kyle
employee table
id
employee_id
name
5
4
Will
6
13
Kyle
Now, on the employee table let's say I'd like to copy what's on my staging table currently, using the INSERT SELECT INTO statement, Paul will be inserted but I don't want Kyle to be inserted since he's on the employee table already(employee.employee_id is the defining column).
I know this could be done by just setting a unique or primary key, on employee_id and just using the statement ON DUPLICATE KEY UPDATE then do nothing by just setting them back to their original values.
I'm new to SQL, and I'm stuck with the solution setting a UNIQUE key and ON DUPLICATE KEY UPDATE statement, but I'd like to know how to do this without that solution I mentioned?
First of all, you should keep in mind that the decision whether to create unique or primary keys or not does not depend on how to create insert statements or such. It's a matter of what your table should do and what not.
In order to achieve your goal, you can add a where to your insert statement which excludes the already existing entries, as example:
INSERT INTO employees (id, employee_id, name)
SELECT id, employee_id, name
FROM staging
WHERE employee_id NOT IN (SELECT employee_id FROM employees)
Break the problem down into its constituent parts
get a list of employees who are in the staging table but not in the target table
insert those records only
Part 1 can be achieved with a Left Join and Where condition that the target table is null. Wrap that up as a CTE and then use it in 2)
Essentially I have the following called Table1 with columns OrderNum and Book there should never be duplicate records of any kind of Book for each OrderNum, if there is it needs to identified and deleted.
For example:
OrderNum 1 should only have Book1 listed once so the query must identify the other 2 Book1 listed for OrderNum 1 and delete them.
OrderNum 4 should only have Book2 listed once so the query must identify the other Book2 listed for OrderNum 4 and delete it.
After the query runs Table1 Should look like this:
I am working with MS Access queries but I am looking for a solution that could work for an mySQL query as well.
I don't know how to do this gracefully on either MySQL or Access, because your table doesn't have a primary key column, which it rightfully should have. On Access, you could try creating a new table, then populating it using the following query:
INSERT INTO yourNewTable (OrderNum, Book)
SELECT DISTINCT OrderNum, Book
FROM yourTable;
Then, delete yourTable after you are done with the above query.
If you had a primary key/auto increment column in your table, let's say id, then you could use the following delete statement directly:
DELETE
FROM yourTable t1
WHERE EXISTS (SELECT 1 FROM yourTable t2
WHERE t2.OrderNum = t1.OrderNum AND
t2.Book = b1.Book AND
t2.id < t1.id);
This would leave, for each (OrderNum, Book) combination, the single record among duplicates which happens to have the lowest id value.
I have a MySQL database table that logs site searches. If it encounters a new search phrase it inserts a new row with the phrase and a counter value of 1. If the phrase already exists it increments the counter.
For example:
Id term count
1 boots 14
2 shirts 2031
3 t-shirt 1005
4 tshirt 188
Unfortunately the table contains duplicates for many phrases, for example:
Id term count
12 sneakers 711
26 sneakers 235
27 sneakers 114
108 sneakers 7
What would a MySQL query look like that combines all the duplicates into one row, totaling up their counts?
What I want:
Id term count
12 sneakers 1067
Thank you in advance.
You are looking for the SUM() aggregate function:
-- `count` is a reserved word so must be enclosed in backticks
SELECT MIN(Id) AS Id, term, SUM(`count`) AS `count` FROM tablename GROUP BY term;
In this case however, if this result is what you want on a permanent basis, I would do as follows:
-- Create a table identical to the current one
CREATE TABLE newtable (Id integer not null auto_increment, term ...)
-- Create a UNIQUE index on the term column
CREATE UNIQUE INDEX newtable_term_udx ON newtable(term);
-- Populate the table with the cleaned results
INSERT INTO newtable (term, `count`) SELECT term, SUM(`count`) ...as above
-- rename the old table as backup, rename newtable with the same name as old table
Then whenever you do an INSERT into the table (which is now the new table) do
INSERT INTO tablename (term, `count`) VALUES ('new word', 1)
ON DUPLICATE KEY UPDATE `count`=`count`+1
This way, if the new term does not exist it will be created with an initial count of 1, and if it does exist, its count will be incremented by 1, all automatically.
select min(Id) as Id, term, sum(count) as count
from your_table
group by term;
Alternatively, you can use max(Id), depending on if you want the first or last Id value for each term.
You can play around with the query here: db-fiddle
Let's suppose I have the following table in a MySQL DB
Table: Debt
ID | Customer | Amount
---------------------
1 | Peter | $ 80
2 | John | $120
What I want to do is sum a new amount of money to the already pending one for a given customer. What I've been doing so far is a SELECT to check if the customer exist in the table. If it does then I UPDATE the register with the sum of the previous value plus the new one. If the register doesn't exist the I proceed to INSERT.
As you can see I'm using two operations, a SELECT and an UPDATE, or a SELECT and and INSERT.
My question is if there is a way to do this with only one single operation
https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html
Set amount = amount + ?? in the on duplicate update clause.
MySql does allow to update an existing record or insert one, use INSERT INTO table (id, name, amount) VALUES (1, 'Peter', 80) ON DUPLICATE KEY UPDATE;
I don't know though if you could use the existing value to do a sum with the new and insert the result.
Probably you'd need triggers for that...