⌘BABAKOV.NET Let's code!
100% [light] [ru]

MySQL Without Loops (One Script).

Here I will provide some examples of useful MySQL queries that I think many people may find useful. At least, when I was looking for such information, I couldn't find anything worthwhile. So I came up with it myself. The data queries will help save time and not write procedures for data processing, which work much slower, or help make these procedures significantly faster. Queries show how in MySQL you can make changes to records in a table, with iteration over all necessary values and with checking necessary conditions but without any loops, only using MySQL means in one query.

So let's get started:

Inserting data from a query into a table:

insert into `Table1` (`Field1`,`Field2`) 
select `Table2`.`Field1`, `Table2`.`Field2` 
from `Table2` where `Field1`=0



This script will insert data from table Table2 into table Table1 that meets the specified condition.

If we want to add table Table1 with data from a query, it can look like this:

insert into `Table1` (`Field1`,`Field2`) 
select `Table2`.`Field1`, `Table2`.`Field2` 
from `Table2` 
where (`Field1` not in(select `Field1` from `Table1`))



Thus, only those records from the query will be inserted that are not in Table1 (meaning not with the value of field Field1).

Also, I think it will be interesting to show an example of changing values in one table by filling these values from another.

update `Table1` set `Table1`.`Field2`=(select `Table2`.`Field2` from `Table2` 
where `Table2`.`Field1`=`Table1`.`Field1`)



This script will change values in table Table1 by replacing them with corresponding values of Field1 from table Table2.

It can all be done with more complex conditions and nested queries.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.