Select and Insert MySQL with distinct record - mysql

INSERT INTO numbers (type, number)
VALUES 'telephone', SELECT DISTINCT tel FROM flat_data
I am attempting to select distinct numbers from one table and then insert them into another table.
However I need to manually set the type column that I am inserting into manually.
I can do it without the DISTINCT but I can't get my head around how to do it with!

INSERT INTO numbers (type, number)
SELECT DISTINCT 'telephone', tel
FROM flat_data

Related

Insert on specific column using Select then normal struct on other columns

INSERT INTO product (pname,currency,other,fields) VALUES ('aNewProduct',(SELECT STATEMENT FOR OTHER VALUES)
is this possible, ive tried to search but they all give me like
INSERT INTO product (pname,currency,other,fields) VALUES (SELECT STATEMENT FOR ALL VALUES)
but i only need specific columns from SELECT and a prefilled column using normal format.. how will this be possible?
You would do it like this:
INSERT INTO
product (pname,currency,other,fields)
(Select 'aNewProduct', currency, other fields... From Tablex where blah)

Insert in a table 2 values

I need some help again.
I have to insert two values in a table into "hospital_database". This table has five columns, and it's called "personas". The columns' names are "cod_hospital(PK)", "DNI", "Apellidos", "Funcion" and "Salario"... I have to insert "99887766" and "Martínez Martínez, Alejandro" into "DNI" and "Apellidos", but according to the question, I must to insert into a "hospital" where only there's 1 person...
I have to use "insert+select" and my last effort was this:
insert into personas
values (99887766, 'Martínez Martínez, Alejandro');
select dni, apellidos
from personas
where count(dni)=1;
I tried something like that, and a lot of ways... but It doesn't work like the question asks. I have to use insert+select, so I shouldn't write ";" before "select".
Honestly I'm still guessing at this a little, but maybe you intend to insert an additional row in the personas table if only 1 row exists in that table for a given hospital code. To do this you need to use group by with having:
insert into personas (cod_hospital, dni, apellidos)
select cod_hospital, 99887766, 'Martínez Martínez, Alejandro'
from personas
group by cod_hospital
having count(*)=1
insert have several sintaxis and looks like you are mixing all of them
One is insert values http://www.w3schools.com/sql/sql_insert.asp
INSERT INTO table_name
VALUES (value1,value2,value3,...);
the other insert from a select
http://www.w3schools.com/sql/sql_insert_into_select.asp
INSERT INTO table2
SELECT * FROM table1;
And if you dont include all the field, you have to indicate which fields are you inserting
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');
cod_hospital is the table's PK, you could only insert one person per hospital, change your PK to: cod_hospital, dni

mysql insert record without using 'values'

INSERT INTO class
(name, description, personid)
Select name, description, 12 from Class where PersonID = 3;
Select * from Class
Select * from Person
Why is the values words is missing from above statement? I thought it should be like this insert into tableA('name') values('select name from tableB') ?
INSERT INTO my_table VALUES ()
Insert data one Table to another table
OR
Not Using Value keyword
Insert into Table2 (Name , Address , Mobile) Select Column 1, Column 2 , Column 3 From Table1
There are different techniques of INSERT, the code above is inserting values from the table itself and change only the personid to 12, he use select so that he can copy the data aside from hardcoded personid . that's why you didn't see the VALUES keyword , but that's true.. the basic insert statement we learn from school is INSERT INTO TableName (Col1, Col2... etc) VALUES (Value1, Value2... etc) , INSERTION of data depends on the requirements that you are working on.

SQL query to join two tables, adding new records if records missing

I have two tables, both with same data:
IP address | count
I need to combine the two tables into new one that contains data from both original tables.
IF there is a matching record in both tables, their count should be added.
IF there is a record that exists only in one table it gets copied over to the new table.
Let first table be called ip_data_january, second called ip_data_february and the one I am trying to create is ip_data_yearly. Thanks in advance.
1st insert only new ip addresses (with count starting at zero)
insert into ip_data_yearly (ip_adress, count)
(select distinct ip_address, '0' from jan_table
where ip_addess not in (select ip_adress from ip_data_yearly);
2nd update the count
update ip_data_yearly y
set count= count +
(select count(j.ip_adress) from jan_table where j.ip_adress=y.ip_adress);
..
3rd do this for all months
You can use ON DUPLICATE KEY UPDATE
I Assume Unique index on IP_Address .. then
INSERT INTO ip_data_yearly (ip_adress)
SELECT IP_Address FROM IP_Data_January
UNION ALL SELECT IP_Address FROM IP_Data_February
ON DUPLICATE KEY UPDATE `count`=`count`+1;
If the IP_Data_Yearly table is empty, an INSERT with a subquery that aggregates count by IP should do the trick:
INSERT INTO IP_Data_Yearly
SELECT IP_Address, SUM(Count)
FROM (
SELECT IP_Address, Count FROM IP_Data_January
UNION ALL SELECT IP_Address, Count FROM IP_Data_February
) IPCombined
GROUP BY IP_Address

INSERT INTO with SubQuery MySQL

I have this Statement:
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1));
I'm trying to insert a value copy the same data of item_costprice, but show me the error:
Error Code: 1136. Column count doesn't match value count at row 1
How i can solve this?
Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
SELECT
/* Literal number values with column aliases */
1 AS item_code,
2 AS invoice_code,
item_costprice
FROM qa_items
WHERE item_code = 1;
Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice, but in a normal SELECT you'll need the aliases to access the columns returned.
You can just simply e.g.
INSERT INTO modulesToSections (fk_moduleId, fk_sectionId, `order`) VALUES
((SELECT id FROM modules WHERE title="Top bar"),0,-100);
I was disappointed at the "all or nothing" answers. I needed (again) to INSERT some data and SELECT an id from an existing table.
INSERT INTO table1 (id_table2, name) VALUES ((SELECT id FROM table2 LIMIT 1), 'Example');
The sub-select on an INSERT query should use parenthesis in addition to the comma as deliminators.
For those having trouble with using a SELECT within an INSERT I recommend testing your SELECT independently first and ensuring that the correct number of columns match for both queries.
Your insert statement contains too many columns on the left-hand side or not enough columns on the right hand side. The part before the VALUES has 7 columns listed, but the second part after VALUES only has 3 columns returned: 1, 2, then the sub-query only returns 1 column.
EDIT: Well, it did before someone modified the query....
As a sidenote to the good answer of Michael Berkowski:
You can also dynamically add fields (or have them prepared if you're working with php skripts) like so:
INSERT INTO table_a(col1, col2, col3)
SELECT
col1,
col2,
CURRENT_TIMESTAMP()
FROM table_B
WHERE b.col1 = a.col1;
If you need to transfer without adding new data, you can use NULL as a placeholder.
If you have multiple string values you want to add, you can put them into a temporary table and then cross join it with the value you want.
-- Create temp table
CREATE TEMPORARY TABLE NewStrings (
NewString VARCHAR(50)
);
-- Populate temp table
INSERT INTO NewStrings (NewString) VALUES ('Hello'), ('World'), ('Hi');
-- Insert desired rows into permanent table
INSERT INTO PermanentTable (OtherID, NewString)
WITH OtherSelect AS (
SELECT OtherID AS OtherID FROM OtherTable WHERE OtherName = 'Other Name'
)
SELECT os.OtherID, ns.NewString
FROM OtherSelect os, NewStrings ns;
This way, you only have to define the strings in one place, and you only have to do the query in one place. If you used subqueries like I initially did and like Elendurwen and John suggest, you have to type the subquery into every row. But using temporary tables and a CTE in this way, you can write the query only once.