Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    MYSQL




Update All Tables


Is it possible to update all tables in my DB on one query




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Update Multiple Tables?
situation:
a user wants to change their username on my site and their username is littered accross many tables in the DB. If in every one of those tables i've got a static "user_id" column as well as the "username" column, what is the best way to update all of the different tables with the most efficiency?


Update - Mult Tables
Early experimentail stages with Databases. I have this little faq sys running on my dev server BUT just uiploaded to my host and what yer know it aint working..

two tables question and answers
two "Poted vars" $an and $id

I am trying to update the answer to a qu....

UPDATE answers,questions SET anstext = '$an' WHERE questions.ans_id = answers.id AND questions.id= '$id'
I read that multiple tables was only suppoerted on later vers on Mysql...OR is my syntax just wrong

How To Update Two Or More Tables Simultaneously
How can I update two or more tables simultaneously with single update query ?


Update 3 Tables At A Time
i have 3 tables namely--- artist, journalist and songs.
i try to update the flags in artist and journalist and try to update few fields from songs by firing foloowing qurries.

update songs set sname='lala', sname2='my baby' where artistid=6;
update artist set statusartist='new',flag1='updated' where artistid=6;
update journalist set statusjourn='new',flag1='updated' where journid=4;

when i fire the above querries individually they are excuted without any error.
when i try to run these querries through my JSP application only the songs data is updated and the rest 2 tables are not.

i tried to write 1 combined query including all 3 tables for this,but still it didnt work.
can u please tell me a solution for this.

Best Way To Update Multiple Tables At Once
I need to update a few tables at once. I have a form, were I fill in some information about a concert, which updates thez concert-table. Next to this, I need to update the bands-table, the statistics-table, and some others. What would be the safest, and fastest way to achieve this?

Update Query Between Two Tables
I am having a problem with getting an update query to work. here's what I am using:
Update stck Set vendor = 'items.vendor' where prtn = 'items.prtn'

I am getting a items table not found error.  I thought this is what I needed to do to update many records from one table to another.

UPDATE Linking Other Tables
I am trying to do a simple update function in mySql.
NOTE. I am using version 3.0.9.4-beta

I have 2 tables:
Items and Sales_details

I want to update a field called >Sales_value< in Sales_details table using value from Items called >Sell< times (*) >Sales_qty< from Sales_details table.

This is the codes I have been trying:

UPDATE Sales_details inner join Items on Sales_details.fk_Item_ID = Items.Item_ID
SET Sales_details.Sales_value = (Sales_details.Sales_qty * Items.Sell)

Error msg:[development_DB] ERROR 1064: You have an error in your SQL syntax near 'inner join Items on Sales_details.fk_Item_ID = Items.Item_ID
SET Sales_details.S' at line 1

and

UPDATE Sales_details
SET Sales_details.Sales_value = (select (Sales_details.Sales_qty * Items.Sell)
from Items inner join Sales_details on Items.Item_ID = Sales_details.fk_Item_ID)
where Sales_details.fk_Item_ID = (select Item_ID from Items)

Error msg:[development_DB] ERROR 1064: You have an error in your SQL syntax near 'select (Sales_details.Sales_qty * Items.Sell)
from Items inner join Sales_detai' at line 2

UPDATE With Related Tables?
I have a forum structure stored in a MySQL database and recent changes I made to a web site using it made it stop incrementing the "replycount" for threads (yup, pretty silly :-)) anyways, I am working on a stored procedure (or just an SQL statement) that I can call to recalculate the reply counts.

The two tables are structured like so:

mysql> describe thread;
+------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+----------------+
| tid | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(50) | YES | | NULL | |
| lastpost | datetime | YES | | NULL | |
| viewcount | int(11) | YES | | NULL | |
| replycount | int(11) | YES | | NULL | |
| author | int(11) | YES | | NULL | |
+------------+-------------+------+-----+---------+----------------+
6 rows in set (0.01 sec)

mysql> describe post;
+----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+----------------+
| tid | int(11) | YES | | NULL | |
| pid | int(11) | NO | PRI | NULL | auto_increment |
| authorid | int(11) | YES | | NULL | |
| body | text | YES | | NULL | |
+----------+---------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

Is there a way to do an update query that will link the two tables, then group on the 'tid' field, then use the count result from the 'tid' field to inset into 'replycount'? Also, this is an example showing how the info is related, just in case I dont make it clear enough to understand:

SELECT thread.tid, thread.title, count(thread.tid)
FROM thread, post
WHERE thread.tid=post.tid
GROUP BY thread.tid

How Do I Automatically Update Tables?
I need some very basic information and ,being new to mysql, am not sure what keywords to use to search for an answer. Would someone please tell me either where I can find the info I seek or what they keywords would be?

I have created three tables and added foreign keys from tables 1 and 2 to table 3.

Example:
#1
person table
person_id pr key

#2
location table
loc_id pr key

#3
event table
event_id pr key
foreign keys: person_id & loc_id

Please note that these table examples have more columns than what is being shown.

When updating the event table, how do I get the foreign key colums to choose the correct person_id and loc_id and automatically update? So far, the mysql tutorial book does not address this in their examples so I must assume that the foreign key columns were updated manually.

Others have told me that this can be done using forms and subforms. If this is so, how?. And, can it not be done also in mysql using the command line?

If forms is part of the answer, I am familiar with them, having used them in my website. I am learning php and have created test forms to update my tables. So far, I can't get the tables to actually update although the php code states that I have connected to both the database and table but that is another issue. My point is that I have some knowledge of forms and php.

I just can not find any info telling me how the forms, subforms, php and mysql may work together to automatically update the tables.

How To Update Tables Automatic?
I have a table with all FOREIGN KEYS pointing to tables with PRIMARY KEYS. But when i add data to base table(Primary Key) it should auto update the dereived(Foreign key) table

Live Update Of Tables
I do have the following problem:
A local server running MySql includes the database A, another server in another region (connected to the internet) includes a mirror database of A. What I need is to live update the tables of the mirror database via a secure connection. Both networks have an internet connection.

Using Form To Update 2 Tables
how to change ths script below so it can update the same cells in another table aswell the current table. in other words updates two tables at the same time.


<?php
if ($submit) {

require("db.php");
$con = mysql_connect("$db_host", "$db_user", "$db_pass");
$db = @mysql_select_db("$db_name",$con);
$sql = "INSERT INTO support (prod_code,prod_name) VALUES ('$prod_code','$prod_name')";
$result = mysql_query($sql);
echo "Thank you! Information entered. <a href=admin.php>Click Here</a>
";

} else{

?>

<form method="post" action="<?php echo $PHP_SELF?>">
Product Code:<input type="Text" name="prod_code"><br>
Product Name:<input type="Text" name="prod_name"><br>
<input type="Submit" name="submit" value="Enter information">
</form>

<?php
}
?>

UPDATE Multiple Tables Difficulties
I've been creating a stock update system that needs to be integrated with an existing database. To update the stock I need 2 tables updated in the same query (unless there is better way).

In one table, items_ordered, holds every single product that has been sold and has a field StockUpdated which holds a 1 or 0 depending on whether they have been stock counted already. This will stop future queries counting stock that has already been counted. i.e. the query will look and update each record that has a 0. So far the query is able to update this table successfully.....

Compare 2 Tables And Update One If A Match.
I have two tables "contact_tbl" and "address_tbl". I have a query that compares the email addresses between the two. If a match is found I need to update a specific field in "contact_tbl" with a value of 'yes'. My query is:

SELECT * FROM contact_tbl
INNER JOIN address_tbl
ON contact_tbl.email = address_tbl.email;

This works and I get a nice result set showing records where the email addresses match. I now need to update a field "status" in contact_tbl when there is a match. Have been tinkering with this for a while but not sure of the syntax and placement for the UPDATE code.

PROGRAM TO UPDATE DATA TABLES
I need to be able to DELETE selected record & LOAD DATA from a text file or Foxpro table, from a program that can run continuously.

I've tried Foxpro, but FoxPro views are too slow. I have also tried issuing these command from Foxpro with an ODBC connection established, but that does not work at all.

The object is to remove all records for a member and replace these records with records from a new file.

Each transaction will be up to 50,000 records.

I need to execute 2 commands:
DELETE FROM parts WHERE parts.member_id="xxx"
and
LOAD DATA INFILE 'd:/xxx.txt' INTO TABLE parts

Can't Update Records When Using Linked Tables In Access
I have a linked table to MySQL 5.0 through MS Access 2003 that utilizes a timestamp field in order to prevent the #Deleted signature happening everytime I create a new record. However, when I attempt to update a previous record I receive the error message: "Reserved error (-7776)" and am subsequently prevented from updating any records. Please note, there are no errors when creating new records, only when I attempt to update an existing one. However, if I remove the timestamp field, updates occur without error. Has anyone else encountered this issue? How might I rectify it?

Complex Query - UPDATE Within UPDATE?
Edit: Before anyone leaves this thread, don't be put off by the regular expressions! They are not the problem, so please stay and read.

OK, this query has got my head spinning. I am basically creating a query that goes through each product in a table to update the stock for that particular item with that particular size (i.e. I am talking about shoes - different models and each model has different sizes (uk kids 12 -> uk 11).

With each shoe it does (or is meant to do) the following:
1. The PHP script that runs the query is looping through every size outside of the query
2. So for each of these sizes it checks to see whether the product it is currently on matches the size it is on
3. When it finds the size it is on, it then deducts the correct number of units from the stock table
4. The final WHERE clause makes sure this subquery inside the UPDATE only happens when the StockUpdated field of the Product table equals 0 (in other words, the stock hasn't been counted before)

Basically what I need to do, is first to make sure what I currently have got does the above correctly but also I need the query to UPDATE the StockUpdated field to 1 only when it has been updated successfully. How could I do this? Unfortunately I cannot just add an extra update entry to the end of the query as this would update the StockUpdated field regardless of whether it has been properly counted or not.

Here is the query I have so far (with a little simple PHP around it doing the loop):


PHP

$shoesizes = array(1 => 'ukk12','ukk13','uk1','uk2','uk3','uk4','uk5','uk6','uk7','uk8','uk9','uk10','uk11');
    $numshoesizes = count($shoesizes);
    
    for($i = 1; $i < $numshoesizes; $i++) {
        $stockupdate = "
        UPDATE heelys_stock,items_ordered SET heelys_stock.size_".$shoesizes[$i]." =
            (SELECT
                CASE
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?( )?(Kids)?( )?( )?(UK)?( )?( )?(Kids)?( )?( )?[^0-9]12( )?(' -- if UK Kids 12
                THEN heelys_stock.size_ukk12 - (items_ordered.Amount/items_ordered.Price)
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?( )?(Kids)?( )?( )?(UK)?( )?( )?(Kids)?( )?( )?[^0-9]13( )?(' -- if UK Kids 13
                THEN heelys_stock.size_ukk13 - (items_ordered.Amount/items_ordered.Price)
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?(UK)?( )?[^0-9]1( )?(' -- if UK 1
                THEN heelys_stock.size_uk1 - (items_ordered.Amount/items_ordered.Price)
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?(UK)?( )?[^0-9]2( )?(' -- if UK 2
                THEN heelys_stock.size_uk2 - (items_ordered.Amount/items_ordered.Price)
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?(UK)?( )?[^0-9]3( )?(' -- if UK 3
                THEN heelys_stock.size_uk3 - (items_ordered.Amount/items_ordered.Price)
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?(UK)?( )?[^0-9]4( )?(' -- if UK 4
                THEN heelys_stock.size_uk4 - (items_ordered.Amount/items_ordered.Price)
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?(UK)?( )?[^0-9]5( )?(' -- if UK 5
                THEN heelys_stock.size_uk5 - (items_ordered.Amount/items_ordered.Price)
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?(UK)?( )?[^0-9]6( )?(' -- if UK 6
                THEN heelys_stock.size_uk6 - (items_ordered.Amount/items_ordered.Price)
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?(UK)?( )?[^0-9]7( )?(' -- if UK 7
                THEN heelys_stock.size_uk7 - (items_ordered.Amount/items_ordered.Price)
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?(UK)?( )?[^0-9]8( )?(' -- if UK 8
                THEN heelys_stock.size_uk8 - (items_ordered.Amount/items_ordered.Price)
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?(UK)?( )?[^0-9]9( )?(' -- if UK 9
                THEN heelys_stock.size_uk9 - (items_ordered.Amount/items_ordered.Price)
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?(UK)?( )?[^0-9]10( )?(' -- if UK 10
                THEN heelys_stock.size_uk10 - (items_ordered.Amount/items_ordered.Price)
                WHEN SUBSTRING_INDEX(items_ordered.Product,',',-1) REGEXP '( )?(UK)?( )?[^0-9]11( )?(' -- if UK 11
                THEN heelys_stock.size_uk11 - (items_ordered.Amount/items_ordered.Price)
            FROM items_ordered WHERE items_ordered.StockUpdated = 0)
                
            WHERE (heelys_stock.id = (SELECT heelys_stock.id FROM heelys_stock,heelys_shoe WHERE SUBSTRING_INDEX(items_ordered.Product,',',1) = heelys_shoe.full_shoe_name))
        , items_ordered.StockUpdated = 1" // at the moment this last update of the items_ordered table happens to every record!!! even if the other part of query fails

        
        // update stock for size $i
        mysql_query($stockupdate);
    }

Hope someone can see how I can do this? I've been working on this query for 2 or 3 hours now and I've been making reasonable progress but now I am really stumped.

Update Replication, Force Update
Recently an error in the db on my master caused the slave to fail. I noticed this after a few days when I looked at the status and it said "Slave_SQL_Running: No". After looking further I saw what the error was on the master.

What is the best method of re-synching the databases?

Is there a command to force a re-replication or synch of the dbs? Would you delete the slave's db and update over? In this case, is there a command to pull the data down from the master?

Unable To Update - Have Update Priveledge
I've been granded update priveledge to tables in a few databases on our server:

Select_priv ,Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, References_priv, Index_priv, Alter_priv, Create_tmp_table_priv, and Lock_tables_priv are all set to 'Y' for a selected database.

I can connnect and read the data and data definitions just fine.  I cannot insert, update, delete, create, or alter any table in this database.

Our admin worked for a couple of hours yesterday trying to resolve the issue, but no joy.  I've googled for this problem and the most relavent posts I've found were problems related with users not being able to connect. I can connect and I can read, I just can't do any of the other priviledges.

ON DUPLICATE KEY UPDATE - Don't Have A Key But Want To Update
This may seem like more of a PHP question but I will come onto the MySQL part in a minute.

Basically I have a PHP script that lets users upload 2 different CSV files to different tables. The problem I have is that sometimes these CSV files are updated and then need to be reimported into the database through the script. I have made this script totally generic so that when you change the table that is being entered to the rest of the script will alter itself to import the correct CSV to that table. But a problem arises when I have a CSV file that contains each product sold and the shopper who bought the product (so the shopperID may appear in more than 1 row) - however this file does not have a unique id for each row meaning that when I use an INSERT INTO with a ON DUPLICATE KEY UPDATE... it will just insert more rows instead of updating rows because there is now key in the table.

The format of the table is like this (with some example data to show you more clearly):

+-----------+-------------+---------+------+--------+------+
| ShopperID | Product Code | Product | Price | Amount | Units |
+-----------+-------------+---------+------+--------+------+
546733 1315 prod 1 64.00 64.00 0
546733 1316 prod 2 43.99 43.99 0

OK just ignore the last 2 fields - that is a problem with the old system there was which does not add the units up right.

Anyway basically I might have the same shopper ordering 2 things which will come up on different rows - I have 3 things I cannot do:

1. I can't make the ShopperID field the PRIMARY KEY because I have many times where there are 2 rows with the same shopper
2. And I cannot just do an UPDATE when it gets to a duplicate entry because it will overwrite every time it gets to a shopper that already exists.
3. I don't want to add a unique primary key to the CSV as this will mean that the system I am creating loses its ability of being automatic because the person (an admin) that uploads the file will have to make sure that it has that extra field which is auto incrementing.

Does anyone have any ideas on how I can get round this?

Here is my PHP function which contains the query:
PHP

// this function for insert data to csv
function makeINSERTS($text, $table, $tablefields, $correctcsv){
    $insert = array(); //make array for hold data insert
    $i = 0;
    $success = true;
    
    while(list($key, $val) = each($text)){
        // Insert the data
        $insert[$i] = "INSERT INTO ".$table."  VALUES('";
        $insert[$i] .= implode("','", $val);
        $insert[$i] .= "') ON DUPLICATE KEY UPDATE ";
        foreach($tablefields as $k=>$field){
            $insert[$i] .= "`$field`='{$val[$k]}',";
        }
        $insert[$i] = substr($insert[$i],0,strlen($insert[$i])-1);
        // echo $insert[$i].'<p></p>'
        $result = mysql_query($insert[$i]);
        if(!$result) {
            echo 'FAILURE to insert/update any or all of the database form uploaded CSV!<br />'
            $success = false;
            die('Query failed: ' . mysql_error().'<br />');
        }
        $i++;
    }
    if($success == true && $correctcsv == true){
        echo 'SUCCESS in uploading the CSV file to the database!<br />'
    }
    else {
    }
return $insert;
}




Update Queries Do Not Always Update
We are running a MySQL database using PHP to create html pages and forms to update and add information to the db. Sometimes the update query works, sometimes it doesn't - or at least, not permanently. A new record may be added, but five minutes later it has sometimes, but not always, mysteriously disappeared.

Where should I look for a solution? Is there a cache that MySQL creates that may be being accessed unwittingly?

We are using the standard php and MySQL versions that come as standard on a Mac OS X Tiger 10.4.7 server. The browser we are using is Firefox 2.0.4.

Maximum Allowed Tables/db, Fields/tables, Records/table
1)tables that can be created in a MySql database.
2)fields that can be created in a MySql table.
3)records allowed in a MySql table and in a MySql database.
4) allowed joins in a MySql table/database.

Cannot Alias Locked Tables / Join To Unlocked Tables ?
If you manually issue a table lock then query that table, aliasing the table generates an error. If you try to join the table to another table that is not locked, you will receive an error. What is the reason for this?

Multiple Smaller Tables V.s. Fewer Bigger Tables
What is the best way to store data in a database? Multiple smaller tables (which means many Inner/Left Joins when fetching the information) or fewer bigger tables (which means few or no Inner/Left Joins when fetching information).

InnoDB Tables And MyISAM Tables In ONE Database?
My application demands some advantages from InnoDB and some from MyISAM.

Is it attainable to have both InnoDB tables and MyISAM tables in ONE database?
Or else, getting views from two databases, one from InnoDB and the other from MyISAM?

If not possible, any other approaches will do the job?

How To Get The SUM Value From Two Tables? Join Tables? Subquery?
Hi,
I have two tables:

table A

Id. | id_result | value
1 | 1| 10
2 | 1| 11
3 | 2| 7
4 | 2| 13

table B

Id. | id_result | value
1 | 1| 4
2 | 1| 1
3 | 2| 5
4 | 2| 6


How can I get sum of unique keys from table A and B (id_result) like this?:

id_result | sum_table_A | sum_table_B
1 | 21| 5
2 | 20| 11

I can do it with UNION or 2 separate SQL statement, but how to make it in 1 query or using subquery?

100 Databases, 4 Tables Each, Or 1 Database, 400 Tables
I was able to build, tweak and do whatever necessary to establish a rather different project but am worried that it may sooner or later crash due to idiotic programming / database usage.

In essense I took 1 database with 4 tables and duplicate it 100 times BUT because I need to connect to the different tables within the php script and am not experienced enough to created nested database connections, I duplicate the 400 tables within the same database.

What I want to know from a MySql perspective, would it make any difference if the script "play around" with 1 database connection and 400 tables or would 100 databases with 4 tables each be better? (Maximum database queries to only 17 tables at a time)

More Tables, Or Huge Tables?
i'm opening a web-service where people can open their own sites.
i have about 18 tables for a website to be put on the air.

i wonder what's better for my users:
one huge table with a lot of rows, or opening 18 new tables in a database in the format:
0_users
0_images
1_users
1_images
2_users
2_images

what's better performance wise? for 1000 users? for 10000 users? 100k users?
i assume that in about 20k users i'll have to get a standalone db server..

How Can I Tell If My Tables Are MYISAM Tables Or What?
Is there a MySQL commad to determine what table type existing tables in a
database are?

Small Tables Or A Few Big Tables
My Web site is going to use a MySQL database extensively throughout the
Web site. It is a content management system type Web site with lots of
users and written articles and other things. With my database I'm
trying to figure out if I should create big tables that have a lot of
rows in them or if I should create a lot of tables that are very
specific to its data and use a lot of table joins in my select
statements. I'm mostly concerned about performance.

I'm thinking that if I make a lot of tables, then select statements I
do will be really fast because my tables won't contain very many rows.
But I don't know if this is true or not or if it matters for
performance reasons or not.

In my Web site I have a lot of different kinds of data that could put
in many different tables. But, without data redundancy and without
using extra storage space, I can still make a few big tables, and make
that work. I just don't know which way is best for performance --
speed, I want speed. Anybody know what I should do or know a book I
should read or a Web site to go to?

Need To Update PK Of Every Row
I want to update every row's primary key and need an SQL statement to do it.

There are 2 columns
PK
Placename

So I firstly want to order all the rows by placename in alphabetical order and then starting by updating the first row to 1, I then want to update every ID with an increment of one - all the way until the final row is updated.


Log Update In My.ini
If i put

log-update=update

in my ini it works fine,but as soon as try to specify a different location i.e.

log-update=/backups/update

i cannot access mysql. I have a folder called backups in the data folder and one in the MySQL Server 5.0 folder (just incase), but it still will not work.

Update If?
I have a table that has an item field, a price field, a price min field, a price max field.

I want to be able to store the current price for an item as well as it's high and low. Is there a way to do an update on the row for the new price as well as compare the new price to the min field and max field and then update them if the new price is either higher or lower than the current values in the min and max field?

I know how to do it with multiple queries and comparing, but am looking for a clean way in one query.

Last Update
Is there a way in mysql to discern when the last date/time a field, row, or
table was been updated or inserted?

Can't Update
I'm current using MySQL and ASP.

But there seems to be a problem when i try to update a particular record. I get the following error message.

Error Type:
Microsoft OLE DB Provider for ODBC Drivers (0x80004005)
Query-based update failed because the row to update could not be found.

Set rs = Server.CreateObject("ADODB.Recordset")
sql = "SELECT * FROM MainPageContents " & _
"WHERE BelongsToShop=" & Session("ShopID") & _
" AND ID=" & which

rs.Open sql, conn, adOpenKeyset, adLockOptimistic

rs.update
rs("some_fld") = "something"
rs.update

I tried setting cursor locations to aduseclient and aduseserver but to no avail. There's also nothing wrong with the query. Does anyone know if there's any kind of issue on updating MySQL using ASP?

Getting A SUM In An UPDATE
I'm trying to update a "parent" table with the sum of data in a "child
table". To illustrate, let's say our database was modeled around a book:

book
-> chapter
-> page
-> attachment (pictures)

The -> represents a one-to-many relationship (e.g. a book has chapters).
Each attachment has a filesize and the parent book has a total_size
(denormalized) column that is the sum of all it's children attachments. I'd
like a query to update total_size in the book table.

Below is what I've come up with thus far. Obviously, it's not working, and
hence my post. The nested SELECT query works fine, but I'm receiving a "You
can't specify target table 'book' for update in FROM clause" error. Code:

Update SQL
I am trying to code a bit of a java app up, and I am sort of learning as I go, so please bear with me for my lack of experence.

I set a table in a database using the following syntax:

CREATE TABLE Instructor(
       FirstName         VARCHAR(20)      NOT NULL,
       Surname           VARCHAR(20)      NOT NULL,
       Title             VARCHAR(20)      NOT NULL,
       DOB               DATE         NOT NULL,
       Address1          VARCHAR(50)      NOT NULL,
       Address2          VARCHAR(50)      NOT NULL,
       Address3          VARCHAR(50)      NOT NULL,
       PostCode          VARCHAR(50)      NOT NULL,
       Telephone         INT          NOT NULL,
       Mobile            INT          NOT NULL,
       Email             VARCHAR(50)      NOT NULL,
       
       PRIMARY KEY(FirstName, Surname));

I create a record with some information (firstname = emma, surname = newton)...

I am then trying to update a record that has been created as follows: Code:

How To Get Key ID For An UPDATE
I need to update a series of fields of a table based on some conditions and get the primary key of affected fields for post-processing the updated rows. Due to the fact that update conditions varies, I do not know what the key field(s) is(are) in advance, so what I want is, when making the update, and in the same transaction, get the primary key of the row that was updated.

What I'm doing now is going through a series of 2 queries per transaction, the update and then a select searchig for the updated row(s) with the updated field content.

I'm working in PHP 5.1.6 under fedora 6. In a worst case, the update will affect up to 10 rows, so I'll need to get all 10 primary keys... the query I'm running is:

$db_query_p3 = "UPDATE message.outgoing SET
pool_lock = '$p3_lock',
engine = '$engine_id',
pool_engine = '$pool_engine'
WHERE pool_status='10' AND (pool_lock < '$lock_expired' OR ISNULL(pool_lock)) AND ISNULL(engine) AND ISNULL(pool_engine) LIMIT 10";

but how to capture the primary key?

When making an insert the transaction return the key with something like:
$insert3 = (@dba_insert_id($db_query_p3))

Update
I want to update 8 rows in a table but these are spaces over the 25 tables. There is a common factor in them all but can't think of a way of doing it.

UDF With Update
I have a lookup table that holds two columns - a key value and another
column containing items. For e.g.

Col1 Col2
1 10
1 15
1 12
2 20
2 15

Anohter table has to be updated with col1 and the max value of col2
for every col1. So ti should look like
1 15
2 20
....

Right now i have a sQL statement that gets the max of the first table
and then does an update on the second. I was thinking about making it
a single query. Multi table update doesnt work here as the order of
updates is not guaranteed.

So i wrote a UDF that will get the maximum value of a column for any
table. So if u call maxfun('Tab1', 'Col2', 1) it will return 15(The
maximum value of col2 in Table1 where col1 = 1).

When i use this in my update
update table2 set column = maxfunc('Tab1', 'Col2', 1)
where column2 = 1;
hangs mysql.
Has anyone tried UDF with update statements?

Update
Is it possible to do update a row with out first doing a separate query... sort of like += in perl or the sum() function?

UPDATE
I have in table 2 rows with same record only field 3 and 4 is different.

field 1, field 2, field 3, field 4
_______________________________________
salcin, elva, 23, 0
salcin, elva, 0, 45


so how can I update or... to have only one row with record like:

field 1, field 2, field 3, field 4
_________________________________________
salcin, elva, 23, 45

So just to get 1 row and where is value 0 and field 1 and 2 same to get "new" value

UPDATE
I have in table 2 rows with same record:

field 1, field 2,  field 3,   field 4
_______________________________________
salcin,   elva,     23,         0
salcin,   elva,      0,         45

so how can I update or... to have only one row with record like
field 1,  field 2,  field 3,   field 4
_________________________________________
salcin,    elva,     23,         45
     

Update
"UPDATE `ItemInformation` SET `LastItem` = 0, `ItemUsed` = 0 WHERE `GameNumber` = $row[0] AND `TeamNumber` = $row[1] AND `LastItem` = 1";

With this code, it's updating `LastItem`, but not `ItemUsed`. Can anyone point me towards a indication as to why?

Update 5.0 To 5.1 Or 6.0 ???
i just upgraded to latest mysql 5.045, should i go to 5.1 or 6.0?? is it worth the pain, do i need to change passwords format like from 4 to 5?

Update
I have about 1000 updates required on a table.

The syntax i know is for example

Update t1 set b_id=9264 where b_id=4259;

and then the next one would be

Update t1 set b_id=9358 where b_id=2253;

etc etc

Is there any way i can run an update with multiple instructions?

UDF With Update
I have a lookup table that holds two columns - a key value and another
column containing items. For e.g.
Col1 Col2
1 10
1 15
1 12
2 20
2 15

Anohter table has to be updated with col1 and the max value of col2
for every col1. So ti should look like
1 15
2 20
....

Right now i have a sQL statement that gets the max of the first table
and then does an update on the second. I was thinking about making it
a single query. Multi table update doesnt work here as the order of
updates is not guaranteed.
So i wrote a UDF that will get the maximum value of a column for any
table. So if u call maxfun('Tab1', 'Col2', 1) it will return 15(The
maximum value of col2 in Table1 where col1 = 1).
When i use this in my update
update table2 set column = maxfunc('Tab1', 'Col2', 1)
where column2 = 1;
hangs mysql.
Has anyone tried UDF with update statements?

Update
I have an address database "address", and I need to update the field "street" row by row for some reason, then when I use

update (select street from address limit 0,1) set street="High Road";

I have a error

nor

update address set street="High Road" where Street= (Select Street from address limit 0,1).

Update 4.x To 5.0
Has anyone made this update?

I'm running on FC4 for our corporate intranet and am running the non-rpm distro of MySQL 4.1.

What is the easiest way to update to 5.0? I don't really see any update scripts or anything to make this update? Is it as easy as untarring the package - installing it just like I did 4.1 and then copy the data files over (certainly it can't be that easy?


Copyright © 2005-08 www.BigResource.com, All rights reserved