MySQL Procedure Insert only if not exists - mysql

I'm using MySQL Stored Procedures and I want to insert some rows from a table's database to another table's database through a stored procedure. More specifically from database "new_schema", table "Routers" and field "mac_address" to database "data_warehouse2", table "dim_cpe" and field "mac_address".
This is the code I used in the first insertion, that worked perfectly.
insert into data_warehouse2.dim_cpe (data_warehouse2.dim_cpe.mac_address, data_warehouse2.dim_cpe.ssid)
(select new_schema.Routers.mac_address, new_schema.Routers.ssid from new_schema.Routers, data_warehouse2.dim_cpe);
Now I have more rows in the table "Routers" to be inserted into "dim_cpe" but, since there are rows already there, I want just to insert the new ones.
As seen in other posts, I tried a where clause:
where new_schema.device_info.mac_address != data_warehouse2.dim_cpe.mac_address
and a:
on duplicate key update new_schema.Routers.mac_address = data_warehouse2.dim_cpe.mac_address"
Both didn't work. What's the best way to do this?
Thanks in advance.

You could leave the source table out of the from clause, and use a not exists clause instead:
where not exists
(select mac_address from dim_cpe mac_address = new_schema.Routers.mac_address
and ssid = new_schema.Routers.ssid)
Or you could left join and check whether the fields from dim_cpe are null:
insert into data_warehouse2.dim_cpe
(data_warehouse2.dim_cpe.mac_address, data_warehouse2.dim_cpe.ssid)
(select new_schema.Routers.mac_address, new_schema.Routers.ssid
from new_schema.Routers
left join data_warehouse2.dim_cpe on
new_schema.Routers.mac_address = data_warehouse2.dim_cpe.mac_address
and new_schema.Routers.ssid = data_warehouse2.dim_cpe.ssid
where dim_cpe.mac_address is null and dim_cpe.ssid is null);
Edit to say this is a general SQL solution. I'm not sure if there's a better MySql-specific approach to this.
Edit to show your query:
insert into data_warehouse2.dim_cpe (mac_address, ssid)
select new_schema.Routers.mac_address, new_schema.Routers.ssid
from new_schema.Routers where not exists
(select data_warehouse2.dim_cpe.mac_address from data_warehouse2.dim_cpe
where data_warehouse2.dim_cpe.mac_address = new_schema.Routers.mac_address
and data_warehouse2.dim_cpe.ssid = new_schema.Routers.ssid);

Related

Insert data from mysql view into a table where not exist

Table will not update when new data is populated in the view. The query runs with no error, but the table is not updated. I'm trying to update the table with data from the view that is not already in the table, based upon the shipping id.
INSERT INTO `table`(`store`, `shippingid`)
SELECT store,shipment_id FROM view WHERE NOT EXISTS (SELECT `shippingid` FROM `table`)
You have to include the correlation between the view and your table:
INSERT INTO `table`(`store`, `shippingid`)
SELECT store,shipment_id
FROM view
WHERE NOT EXISTS (SELECT `shippingid`
FROM `table`
WHERE shippingid = view.shipment_id)
Please note that this query is an INSERT operation, not an UPDATE.
If you have any row in your table this will always be false:
WHERE NOT EXISTS (SELECT `shippingid` FROM `table`)
It seems you might need to add correlation:
WHERE NOT EXISTS (SELECT `shippingid` FROM `table` WHERE shippingid = view.shipment_id)
Please note that, theoretically, sub-queries execute once for every row of outer query. So to understand the flow.. take some sample data and understand how the query will produce results.

Store records in a new table created by a query in mysql

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;

Insert a new record in MySQL table at start

I am new to MySQL and learning it to my own. Actually I want to copy a column from a table into my existing table column! suppose that my existing table is:
where pid values are inserted by default!
now i want to copy a column from another table using:
INSERT INTO exist_tab(FirstLevel) SELECT some_col FROM another_table;
so that the values should come inside FirstLevel Column.
but the problem is that the copies values come below the pid values in FirstLevel Column as:
see that the firstlevel comes below! what is wrong with it? I need the "H" value against 19 but i dont want to use wild cards just want to copy the new data against old column data
thanks
I am new to this kind a work please can somebody give me any idea how to do it please!
thanks in advance
INSERT and UPDATE is different Command to Perform Different Task.
INSERT :Insert New Record into the table
Update:Update Existing Record in table If Exist.
NOT SURE ABOUT IT:(i'm Not Familiar With MYSQL)
Update a set
a.FirstLevel=b.some_col
from
exist_tab a join another_table b on a.Id=b.Id
Or You can Try :
update exist_tab a set a.FirstLevel=
(select top 1 some_col from another_table where Id=a.Id)
EDIT2:
update exist_tab a set a.FirstLevel=
(select top 1 some_col from another_table)
You Can Find Here.
You are using INSERT statement here. INSERT will create a new record in the table. You have to use UPDATE for updating a particular column in the existing table like this:
UPDATE exist_tab
SET FirstLevel = (SELECT some_col FROM another_table)
If you want any conditional update then you can use JOIN like this:
UPDATE exist_tab a
LEFT JOIN another_table b ON
a.pid = b.id
SET FirstLevel = a.some_col;

In SQL, is there an alternative way to see if a record is already there before adding it?

I have a MySQL table like this,
id (primary key) | name | scores
and I am reading a large file to insert records into the MySQL table.
New records will be added into this file but the old records are not deleted, so when I read the file, a lot of records are already in the database.
Except to use SELECT COUNT to see if a record is already in the database, is there a best way to check it (to save processing time & database load)?
Or maybe I should just INSERT it directly? (The database will not allow records with duplicate id anyway.)
I usually use update + insert method.
first i will run the update statement. the update query will act like a select query + directly update the data.
update t1 set t1.Name = 'Name', t1.Scores = 99
where t1.Name = 'Name' and t1.Scores = 99
then check if there is a row affected by the above query. if not run the insert statement
if ##RowCount = 0
insert into t1 (Name, Scores) values ('Name',99)
Serch examples for
INSERT IGNORE INTO table
Simple example for this is
INSERT IGNORE INTO `transcripts`
SET `ensembl_transcript_id` = ‘ENSORGT00000000001′,
`transcript_chrom_start` = 12345
`transcript_chrom_end` = 12678;

Update Mysql Query Optimisation

I must create a mysql query with a large number of queries (about 150,000)
For the moment the query is:
UPDATE table SET activated=NULL
WHERE (
id=XXXX
OR id=YYYY
OR id=ZZZZ
OR id=...
...
)
AND activated IS NOT NULL
Do you know a best way for to do that please?
If you're talking about thousands of items, an IN clause probably isn't going to work. In that case you would want to insert the items into a temporary table, then join with it for the update, like so:
UPDATE table tb
JOIN temptable ids ON ids.id = tb.id
SET tb.activated = NULL
UPDATE table
SET activated = NULL
WHERE id in ('XXXX', 'YYYY', 'zzzz')
AND activated IS NOT NULL