INSERT SELECT query when one column is unique - mysql

I need to call INSERT + SELECT to import user data to different table and I need to filter user_name duplications, So I need something like this:
INSERT INTO new_table SELECT email, distinct user_name, password from old_table
but distinct works only when using distinct email, user_name, password and all those column need to be unique.
Is there any other way to insert select with uniq user_names, (I need only first row - with lower id)?
EDIT I forget to mention that I use mysql

Without testing I would expect something like this to do the trick (assuming the id column is named id)
INSERT INTO new_table
SELECT email, user_name, password
FROM old_table
INNER JOIN
( SELECT MIN(id) FROM old_table GROUP by user_name ) minids
ON minids.id = old_table.id

Related

MySQL - INSERT INTO Table With a New ID

I have two tables and I want to copy a row from one to the other. However they both use an auto incrementing ID number as the primary key which is preventing me from copying a row if the ID already exists in the other table.
What I want to do is:
INSERT INTO tableB SELECT * FROM tableA WHERE ID = 1
What I was thinking might be possible would be to store the row as a variable, temporarily set the ID to be blank, and then it will be assigned the next highest number once inserted into the new table?
Is something like this possible?
Edit:
Columns
ID, Deal_ID, Redeemed_At, Wowcher_Code, Deal_Title, Customer_Name, House_Name_Number, Address_Line_1, Address_Line_2, City, County, Postcode, Email, Phone, Date_of_Birth, Custom_Field, Marketing_Permission, Product_Name, Product_Options
You cannot use * (all columns) in this case .. you must explicitally set the columns you need eg:
INSERT INTO tableB (col1, col2, col3)
SELECT col1, col2, col3
FROM tableA
WHERE ID = 1
avoinding the ID columns
Just select the columns without the ID.
INSERT INTO tableB SELECT name,age,any_other_column FROM tableA WHERE ID = 1
Try replace asterisks with fields list withouth ID
INSERT INTO tableB SELECT Field1,Field2,Field3...FieldXX FROM tableA WHERE ID = 1

MySQL look for duplicates on multiple fields

I have a MySQL database with the following fields:
id, email, first_name, last_name
I want to run an SQL query that will display rows where id and email exists more than once.
Basically, the id and email field should only have one row and I would like to run a query to see if there are any possible duplicates
If you just want to return the id and email that are duplicated, you can just use a GROUP BY query:
SELECT id, email
FROM yourtable
GROUP BY id, email
HAVING COUNT(*)>1
if you also want to return the full rows, then you have to join the previous query back:
SELECT yourtable.*
FROM
yourtable INNER JOIN (
SELECT id, email
FROM yourtable
GROUP BY id, email
HAVING COUNT(*)>1
) s
ON yourtable.id = s.id AND yourtable.email=s.email
You'll want something like this:
select field1,field2,field3, count(*)
from table_name
group by field1,field2,field3
having count(*) > 1
See also this question.
You can search for all ids that meet a specific count by grouping them and using a having clause like this:
SELECT id, COUNT(*) AS totalCount
FROM myTable
GROUP BY id
HAVING COUNT(*) > 1;
Anything this query returns has a duplicate. To check for duplicate emails, you can just change the column you're selecting.

Insert several datasets for several IDs

I have a table of users:
UserID | User
1 Martin
2 Lilian
3 Oliver
Now I have another table:
dataID | UserID | key | value
Now what I need to do is:
Select certain users from the user-table and insert several recrods in the data-table:
I need to combine these two querys:
INSERT INTO `data` (`UserID`, `key`, `value`)
VALUES (HERE_ID_OF_USER, 'someKey', 10),
VALUES (HERE_ID_OF_USER, 'otherKey', 20)
SELECT `UserID` FROM `users` WHERE ...
Not sure I fully understand what you want to do, but I'll assume you want this:
INSERT INTO data (UserID,key,value) SELECT UserID,'somekey',10 FROM users WHERE ...
INSERT INTO data (UserID,key,value) SELECT UserID,'otherkey',20 FROM users WHERE ...
If that's not what you want, you'll need to be a bit more explicit...
Update
If you already have the data you want to insert for each user in a table, you can use:
INSERT INTO data (UserID,key,value)
SELECT u.UserID,dd.key,dd.value FROM users u,default_data dd WHERE ...
If you don't (and don't want to store it in a table), you can use;
INSERT INTO data (UserID,key,value)
SELECT UserID,'some key',10 FROM users WHERE ...
UNION ALL
SELECT UserID,'other key',20 FROM users WHERE ...
or (to avoid the repetition of the WHERE clause):
INSERT INTO data (UserId,key,value)
SELECT u.UserID,dd.key,dd.value
FROM users u,
(
SELECT 'some key' AS key,10 AS data
UNION ALL
SELECT 'other key',20
) dd
WHERE ...
There are probably more ways to do it.
Build your select query to fetch data from 2 table based on User ID join. Then insert the result set into the desired table.
INSERT INTO DATA (SELECT A.USER_ID, B.KEY, B.VALUE FROM USERS A, SECOND_TABLE B WHERE A.USER_ID = B.USER_ID AND A.USER_ID IN (.....))

Inserting data from one table to other but don't want the primary id

I am trying to copy data from one table to another table but I don't want to have the ID column copied into the the new table.
Here is what I have tried so far
INSERT INTO T2 (ID, FIRST_NAME, LAST_NAME)
(SELECT AUTO, FIRST_NAME, LAST_NAME,
FROM T1);
When the table T2 was created the ID was not set to auto-increment since the IDs are going to be generated by the front end app going forward.
Don't know if this has been asked before but please help.
INSERT INTO T2 (ID, FIRST_NAME, LAST_NAME)
(
SELECT (#row:=#row+1) AS rn,FIRST_NAME, LAST_NAME,
FROM T1, (SELECT #row:=0) r
);
check the query at SQL Fiddle: http://www.sqlfiddle.com/#!2/91037/1

inserting records in a MySQL table depending on existing values in another table

I am using MySQL. I want to insert some records in a table provided that they do not
exist in another table. So I want to perform something like this:
INSERT INTO sales (name, id)
SELECT name, id FROM sales_h
WHERE name AND id NOT IN (SELECT name, id FROM T_sales);
The problem is that MySQL does not allow this kind of syntax (something to do with the where clause...) I tried using CONCAT but with no result.
Any clue??
INSERT
INTO sales (name, id)
SELECT name, id
FROM sales_h
WHERE (name, id) NOT IN
(
SELECT name, id
FROM t_sales
)
Have you tried the EXISTS syntax?
INSERT INTO sales (name, id)
SELECT name, id
FROM sales_h
WHERE NOT EXISTS (SELECT * FROM T_sales WHERE T_sales.name = sales_h.name AND T_sales.id = sales_h.id);
MySQL allows you to use a tuple like a variable:
This is your statement:
INSERT INTO sales (name, id)
SELECT name, id FROM sales_h
WHERE name AND id NOT IN (SELECT name, id FROM T_sales);
The problem is "name AND Id". Turn that into a tuple:
INSERT INTO sales (name, id)
SELECT name, id FROM sales_h
WHERE (name, id) NOT IN (SELECT name, id FROM T_sales);
Personally, I don't like this much for two reasons: the tuple as variable doesn't work (or works differently) on other RDBMSes, and IN tends to perform poorly in many situations, so I like to make it a habit not to use IN.
As jhonny-d-cano-leftware states (I've upmodded him), I'd use a where not exists:
INSERT INTO sales (name, id)
SELECT name, id FROM sales_h a
WHERE not exists (
SELECT *
FROM T_sales b
where b.id = a.id and b.name = a.name);
You might look into the ON DUPLICATE clause for MySql
http://dev.mysql.com/doc/refman/5.1/en/insert-select.html
You can't say WHERE name AND id NOT IN... you need a separate clause for each. But do you have id as the primary key in table T_sales? If so, then that's all you need to check for, sp something like:
INSERT INTO sales (name, id)
(SELECT name, id FROM sales_h WHERE id NOT IN (SELECT id FROM T_sales));
EDIT
Hmmm from other people's answers it might be best to ignore me as they seem to know more :-)
The problem is your WHERE.
It's not reading as you are. You're reading it as "WHERE (name and id) NOT IN (...)", whereas it's reading it as "WHERE name (isn't null) AND (id NOT IN (...))"... if you get what I mean.
Change to this: ROW(name, id) NOT IN (SELECT name, id FROM T_sales);
INSERT INTO table_name(column1, column2) SELECT "value one", "value two" FROM DUAL
WHERE NOT EXISTS(
SELECT column1 FROM table_name
WHERE column1 = "value one"
AND column2 = "value two" LIMIT 1
)