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




Updating Rows In Table B Based On Related Field In Table A


Ver 4.1.8-standard for apple-darwin7.6.0 on powerpc (Official MySQL-standard binary)

I am trying to do some data migration based. I have several tables that contain our legacy pkey field and I want to update the tables with new ID's.
I need to do this several times and have tried it several ways to no avail.

Table A
---------
companyID int(10) pKey
legacyID int(10) old legacy pkey

Table B
---------
bAID int(10) pkey
companyID int(10)
legacyID int(10)

Table A has values for both companyID (unique key) and legacyID.
Table B has values for bAID (unique key) and legacyID but companyID is empty.

I need to update tableB.companyID with tableA.companyID based on tableb.cSerialID to tablea.cSerialID relationship.

I need a query that will update ALL rows.




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Updating Table Based Upon Matching Field In Second Table
I have a database of books that was originally created as a flat file.
Each record has a number of fields, including the authors name. I'm
trying to convert the database to something a little more efficient.
I've created a new table (called Authors) of unique authors names and
assigned each one a unique ID. I've added a new field in the original
table (called Books) for the author's ID. Now, I need to update the
original table with the author ID from the Author's table.

Something like this:

UPDATE Books SET AuthorID = Authors.AuthorID WHERE AuthorName =
Authors.AuthorName

This obviously doesn't work. Any assistance on how to forumulate this
query (or, if I'm headed down the wrong path, the correct way to do this
operation) greatly appreciated.

Two Table Query: Grab Rows From One Table Even If No Related Row In Other Table
PHP

$gettray = mysql_query("SELECT trailers.title,
trailers.link,
trailers.movie,
movie.title AS mtitle
FROM trailers,movie
WHERE trailers.movie=movie.word
ORDER BY trailerid
DESC LIMIT 6",$connm);

It works great, but there is one problem. It will not grab any rows from the 'trailers' table if a corresponding movie row does not exist in the 'movies' table.

I want it to pull ALL rows from the 'trailers' table, even if the corresponding row in the 'movies' table does not exist yet.

If the row does not exist in 'movies', the program than uses the entire trailer title like so


PHP

if($ttray['mtitle']) {
  $newttitle = explode("-",$ttray['title']);
$newttitle = array_reverse($newttitle);
$ttitle = $newttitle[0];
$ttitle = $ttray['mtitle'] ."- ". $ttitle;
} else {
$ttitle = $ttray['title'];
}



Thanks
Ryan

Updating A Table Based On The Value In Another Table In Ver 3.23.54-Max
I am trying to update fields in table SOLAR_SYSTEM based on the values in RESEARCH_LEVEL table

This is a SQL that I am trying to use

UPDATE SOLAR_SYSTEM JOIN RESEARCH_LEVEL ON SOLAR_SYSTEM.USER_ID=RESEARCH_LEVEL.USER_ID SET
SOLAR_SYSTEM.CASH_METAL=SOLAR_SYSTEM.CASH_METAL+1000,
SOLAR_SYSTEM.CASH_CRISTAL=SOLAR_SYSTEM.CASH_CRISTAL+1000,
SOLAR_SYSTEM.CASH_ENERGY=SOLAR_SYSTEM.CASH_ENERGY+1000
WHERE RESEARCH_LEVEL.TYPE='M' AND RESEARCH_LEVEL.LEVEL=1;

I got error

"ERROR 1064: You have an error in your SQL syntax near 'JOIN RESEARCH_LEVEL ON SO
LAR_SYSTEM.USER_ID=RESEARCH_LEVEL.USER_ID SET
SOLAR_SY' at line 1"

I don't know what is wrong. Can I do such an update in Ver 3.23.54-Max in the first place ? IF yes, then what's wrong with my statement?

Getting Rows That Are Related To Other Rows In The Same Table
I use a table to save a map using the following structure:

id, x, y, owner

Every occupied map filed has an owner id != 0. The owner id is = 0 for vacant fields.

now the problem:

New registered users need a vacant field on the map. Moreover the mapfields around this field need to be vacant as well! (sqrt((t1.x-t2.x)*(t1.x-t2.x)+(t1.y-t2.y)*(t1.y-t2.y)) <= 5.25)

What I need is a query that gets those fields that have vacant fields around them.

So far, all my tries to solve this problem with Joins/Suvqueries failed.

Updating A Database Field Based On A String Or Filename
I am using MySQL to store images that I serve up with Coppermine photo gallery. Each image is shown in low resolution format. I also store medium and high resolution versions of these files for download. There is a caption field where I put these links using BBcode. It looks something like this: Code:

Detecting Duplicates Based On One Field In A Table?
I can't seem to find an answer anywhere for this as most people want to delete duplicate records.

I have a table, lots of fields, one of which is "title". I want mysql to return all the rows where "title" is the same. For instance if "title" was "Lord of the Rings" on id = 1 and id = 2, then the query would return both of the records, but ignore the others. It doesn't matter what the other field values are.

I have found some
SELECT COUNT( * ) AS num_entries, title
FROM title_table
WHERE title >1
GROUP BY title

But this doesn't seem to work, although looks like it's on the right sort of lines?

I'm not a Mysql expert, so my experience is mostly limited to the usual select, insert, update and delete queries!

Returning Rows In Left Table Based On Mutliple Criteria In Right
This is starting to get to me. I'm sure there's a simple way of handling what i'm trying to do, but someone might be able to help out quicker than spending another hour searching and testing for this. Here's the problem:
Simplified tables:
ARCADES
=======
ID,
name
GAMES
======
ID,
name
ARCADES_GAMES
=============
ID,
arcade_iD
Games_ID
Straightforward enough so far right? I'm trying to get all arcades that have ALL games in a passed in set of game_id's. So for instance I might want all arcades that have the games 11 and 14, but it must have both those.
I can do soemthing like...

SELECT a.name
FROM arcades a
WHERE EXISTS(SELECT 1 FROM arcades_games
WHERE arcade_id=a.id AND game_id IN (11,14))
But that'll return all rows that match ANY of (11,14) rather than ALL of 11,14.

It all comes down to the simple thing of getting rows in a table where all criteria from a list is met, but any advice on how i would do something like this?

Updating Table Field From Another Table Field
I have a field called 'tel1' in table 'live_properties'
and I want to update a 'tel1' field in 'live_properties'

with

'phone_num' field from 'usersTBL'

MYSQL code is here but giving error any suggestions

UPDATE live_properties SET tel1 (SELECT phone_no FROM usersTBL WHERE username = live_properties.username)

Select Rows Where A Field Value Exists In Another Table
I have a table with a column of email addresses I have a second table with a column of email addresses I want to select all the rows in the first table whose email value exists in the second table Can't get a query to do this without an error,

Selecting From A Table Based On Info In Another Table
Essentially this is what i want to do. I have two Tables,

Table A- has the field "id" which is the primary key
Table B- has the field "id" which is the primary key

Select * from tableA where Table A.id is not in tableB.id

How can i form a statement that will accomplish the above.

Selecting From A Table Based On Info In Another Table
Essentially this is what i want to do. I have two Tables,

Table A- has the field "id" which is the primary key
Table B- has the field "id" which is the primary key


Select * from tableA where Table A.id is not in tableB.id


How can i form a statement that will accomplish the above.

Front End For Updating Several Related Tables
Is there a simple front-end that would let me select records from
multiple related tables and edit their field data?

Right now, I am opening each table individually in mysql control center,
entering the new record, or editing the existing one, then moving on to
the next table.

I know there’s got to be something better, and I am to
busy (spelled overloaded) to create my own from scratch. I use python
now for most of my sql scripts, and PHP on occasion, but could figure
out and modify something simple if necessary.

Related Table
I am trying to follow an example I found for creating two tables in a "related form" The code creates the two tables, however if I use PhpMYadmin to enter primary records in the first table, I get an error on trying to add a second record. Code:

DELETE With Related Table
I have a table (tableA), with a data field (saved as a VARCHAR in
YYYY-MM-DD). I have a second table, tableB, which has a field with an int
field which refers to the ID of tableA (or is null). I call this field
tableB.idA

I am trying to delete rows in tableA where the date is less than a specified
value AND there is no reference to said row in tableB.

But how to specify this in SQL. I tried :

DELETE FROM tableA WHERE tableA.date <'2007-01-01' and tableB.idA!=
tableA.id;

only to get the exception Unknown table 'tableB' in where clause.

Forum Related Table Structure
I didn't know whether to post this in the php forum or mysql--we'll try this one:

Suppose that I have a mysql-php based forum running. Users table (simplified) looks like:

Users
------------
user_id (int, primary_key)
username (varchar(30))
password (varchar(30))
read_post_ids (text)


Currently, 'read_post_ids' is a comma-separated list of all the post ids that a user has clicked on, which are marked as such.
Currently a php script is resposible for reading the list into an array, looping through to find values if needed, and on a write back to the db it takes the array and turns it back into a CSV string.

Problem: The table isn't even in 1NF because of this field, and extra processing is going on. As an alternative, I have considered dropping 'read_post_ids' from this table, and starting a new table:

Read_Post_Ids
-------------
id
read_post_id
user_id

This normals the tables and makes queries easier, but I worry about storage. Let's say I have 10,000 forum users, that on average read 20 posts per day. that is 200,000 table rows per day. In a year, I have 71,000,000 rows. If I index the fields (as I probably should for speed), the rows take up even more room. If I decide to only allow a user a maximum of 300 stored 'read posts' (for example), then I probably have to add a timestamp field so I can delete the older ids, which takes up even more space.

So is there a preferred method here? I would prefer that the tables be normaled, but I worry about the table growing out of hand in terms of size, and at some point becoming slow.

Counting Records In Related Table
I'm trying to construct a single query that returns all records from one table plus a count of all corresponding records in another table. I have a table of members (members) and a separate table (traffic) that tracks what each member has downloaded from the website I've created. Here is the current SELECT statement I'm using:

SELECT * , COUNT(*) AS traffic_count
FROM `members` , `traffic`
WHERE members.id = traffic.member_id
GROUP BY members.id
ORDER BY traffic_count

This almost works for me. The problem is that it only returns results for the members who have corresponding records in the 'traffic' table. This is a great start but I'm trying to return all records from the 'members' table including a corresponding 'traffic_count' variable for each member. This means that for each member that has no entries in the 'traffic' table I'd like the 'traffic_count' variable to be 0.

Table Based On Info In Another Table
Essentially this is what i want to do. I have two Tables,

Table A- has the field "id" which is the primary key
Table B- has the field "id" which is the primary key


Select * from tableA where Table A.id is not in tableB.id

How can i form a statement that will accomplish the above.

Updating Table With Reference To Another Table
I am trying to update two columns of a table (date and location) so that they are equal to the date and location of another table on a lastname join. Here's is the code I have right now:

update tblA
    set tblA.date = tblB.date, tblA.location = tblB.location
    where tblA.lastname = tblB.lastname;

I am getting a syntax error with the above code. Does anyone know how to do this?

Query The Article Table And Get A Count Of All Related Comments
Could someone please help me with this query. I have two tables -- one for my articles and another for my comments. Comments are stored in the comments table with a corresponding article id.

I want to query the article table and get a count of all related comments. The following query doesn't seem to work for me. Can you please suggest how I fix it?

SELECT a.id AS id, a.title AS title, a.preview AS preview, a.thumbnail AS thumbnail, a.category AS category, a.timestamp AS timestamp, a.game AS game, count( b.id ) AS commentcount
FROM article_table AS a, comment_table AS b
LEFT JOIN comment_table ON a.id = b.article
WHERE a.news = 'Yes'
AND a.type = &#391;'
AND a.saved != &#391;'
GROUP BY b.article
ORDER BY a.timestamp DESC
LIMIT 5

Delete Rows From Table A, Which Dont Exist In Table B (base On Column X)
I have 2 tables identically structured.

A & B

Table A, has column: Product (product code) as primary key

Table B doesn't.

Apart from that they have the exact same fields.

There's also a column: supplier

I want to

Delete * from table A, where does not exist in B (based on column: Product) & where supplier = apples

So to elaborate. Table A is my main table, but it now contains outdated products from supplier apple. Table B has the latest list of products from supplier apple. So I want to remove old products from A that supplier apple no longer makes.

mysql version 4.0.27

ALTER TABLE Deleted The Rows - Error: Table Is Full
Today when I tried to insert data in a table i received the error that 'table is full'. On SHOW TABLE STATUS, I noticed the size of table is grown to 4GB (rows 5359211).

mysql> SHOW TABLE STATUS LIKE 'messages' G
*************************** 1. row ***************************
Name: messages
Engine: MyISAM
Version: 9
Row_format: Dynamic
Rows: 5359211
Avg_row_length: 801
Data_length: 4294967288
Max_data_length: 4294967295
Index_length: 45783040
Data_free: 0
Auto_increment: 5406252
Create_time: 2007-04-20 18:26:38
Update_time: 2007-08-22 09:55:22
Check_time: NULL
Collation: latin1_swedish_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)
Here is the table structure.


CREATE TABLE `messages` (
`id` int(11) NOT NULL auto_increment,
`subject` varchar(255) NOT NULL default '',
`message` text NOT NULL,
`attachment_path` varchar(255) default NULL,
`new` tinyint(4) NOT NULL default &#390;',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

On searching I found the this link.
http://dev.mysql.com/doc/refman/4.1/en/full-table.html

According to manual i executed the following query

MySQL
ALTER TABLE messages MAX_ROWS=20000000000;
I skipped AVG_ROW_LENGTH from the query, I was confused what should be the value for this.

After executing the query, when i check the table status it displayed totally different picture. Now there were only 170109 rows left.


mysql> SHOW TABLE STATUS LIKE 'messages' G
*************************** 1. row ***************************
Name: messages
Engine: MyISAM
Version: 9
Row_format: Dynamic
Rows: 170109
Avg_row_length: 649
Data_length: 110563036
Max_data_length: 281474976710655
Index_length: 1961984
Data_free: 0
Auto_increment: 5409214
Create_time: 2007-08-23 10:07:08
Update_time: 2007-08-23 13:41:57
Check_time: NULL
Collation: latin1_swedish_ci
Checksum: NULL
Create_options: max_rows=4294967295
Comment:
1 row in set (0.00 sec)
What could be the reason of this rows deletion?

I am on 32 bit system.
MySQL version: 4.1.18-standard-log
Operating System : CentOS 3.x
Memory: 4 GB DDR

Help With Moving Data From One Table Field To Another Table Field
I am a relative newbie at this so would appreciate help - already searched and found and tried several suggestions for similar issues - but nothing quite worked!

I need to move a membership roster to another table in the same db - currently the data is at jos_users1 and it needs to be moved to jos_users. The jos_users1 table has only one field, named email.

The jos_user table has several fields including the email field, and already has data in it - so I don't want to overwrite the table - just upload the additional email addresses into the table.

UPDATE Based On Value In Another Table
How do I update a table to remove orphaned references to a second
table? I've deleted rows in the second table, which has a unique
auto_increment key. The first table now has references to keys that no
longer exist. I need to update the first table, setting the value to
NULL where the referenced key no longer exists. Something like:

UPDATE table1 SET table2ID = NULL WHERE table1.table2ID NOT FOUND IN
table2.ID;

The NOT FOUND IN isn't SQL, of course, but I'm not sure what should go
there.

Update Based On Other Table
I know this is how this query would be written in SQL but I think something isn't working correctly since this is mySQL.

SQL query:
UPDATE watches SET watches.totalhits = ( SELECT COUNT( id ) AS totalhits
FROM watchtracker
WHERE watches.id = watchtracker.watchid )

MySQL said:
#1064 - You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT COUNT(id) as totalhits
FROM watchtracker
WHERE watches

UPDATE Based On Value In Another Table
How do I update a table to remove orphaned references to a second
table? I've deleted rows in the second table, which has a unique
auto_increment key. The first table now has references to keys that no
longer exist. I need to update the first table, setting the value to
NULL where the referenced key no longer exists. Something like:

UPDATE table1 SET table2ID = NULL WHERE table1.table2ID NOT FOUND IN
table2.ID;

The NOT FOUND IN isn't SQL, of course, but I'm not sure what should go
there.

UPDATE Based On Value In Another Table
How do I update a table to remove orphaned references to a second
table? I've deleted rows in the second table, which has a unique
auto_increment key.

The first table now has references to keys that no
longer exist. I need to update the first table, setting the value to
NULL where the referenced key no longer exists. Something like:

UPDATE table1 SET table2ID = NULL WHERE table1.table2ID NOT FOUND IN
table2.ID;

The NOT FOUND IN isn't SQL, of course, but I'm not sure what should go
there.

Updating One Table With Another
My table contains a product number field 'packCode' but some clients may have their own internal product code. I have created a table ('configurators') which contains our product code along with two columns each for clients: their product code and price, i.e.:

packCode, insight_code, insight_price

The client sends me data containing our pack code matched against their product code and price. I wish to merge their data with our price list in the configurators table. The MySQL I have used is:

update configurators
set insight_code=iCode, insight_price=iPrice
where configurators.packCode=config_insight.iPackCode;

(The columns from the client data are preceded with 'i', i.e. 'iCode', 'iPrice' and 'iPackCode')

However, when I run the query, I get the unusual error

"ERROR 1109 (42S02): Unknown table 'config_insight' in where clause"

suggesting that the table 'config_insight' does not exist, which it clearly does. Is this the correct way to merge data from one table into another? Is my SQL query valid or am I missing something?

Updating Table
I'm sure this is possible, probably with a sub-query.I want to update a record with a value from another record in the same table.

E.G.
CODEName     Val_1     Val_2    Check_col
Test1    0         0        s
Test1    10        20       M
Test2    0         0        s
Test2    20        25       M

Updating Table
I have a database table and 1 column has positive and negative values in it.

I want to update the table so that all entries in this column are positive... so all negative values like -3, -2, and -1 become 3,2 and 1 respectively in the table.

Updating Table
I have a database of books that was originally created as a flat file.
Each record has a number of fields, including the authors name. I'm
trying to convert the database to something a little more efficient.
I've created a new table (called Authors) of unique authors names and
assigned each one a unique ID. I've added a new field in the original
table (called Books) for the author's ID. Now, I need to update the
original table with the author ID from the Author's table.

Something like this:

UPDATE Books SET AuthorID = Authors.AuthorID WHERE AuthorName =
Authors.AuthorName .

Updating Table Value
update jobs set paid=true where jobid in (SELECT jobid from jobs where CreatedBYusername='roop')

after executing this query i got an ERROR:

You can't specify target table 'jobs' for update in FROM clause.....
same thing i executed in mssql....how can i do this in mysql

Updating Table
I have two tables:

table1:
id code
1
2
3 aa
4

table2:
id code2
1
2
3 xx
4 zz

I am looking for a way to update table1 with some sort of sql statement. I looked into update and joinn but I couldn't find any relevant information. The reason I don't have any success is prbably because I don't have the correct keyword.

Partially Updating Records Based On Pattern Match
I would like to know if it is possible to a (string) replace on
existing records based on a given pattern.

Let's say I have a table containing the following records (strings):
Windows/98
Windows/98/Registry
Windows/2000
Windows/2000/Registry

Is there an SQL method for scanning all records in the
table for the pattern "Windows/98" and then, when a match is made, replace
only the "Windows/98" part of the string with "Windows/2003"?

I am having a hard time figuring this out.

Help With 3 Table Query &amp; Counting Rows In Third Table
I have three tables, a members, a vendors and a products. I'm using a query to grab all of the rows from the first two tables, matching on a primary key. This is easy and works fine. However, I'm trying to pull the number of products from the third table and it's giving me trouble. Basically, I can count the products for each vendor if products exist, but if there are no products, instead of returning 0, no rows are returning.

current query looks like this:

SELECT t1.*, t2.*, count(*) AS count FROM vendors as t1, members AS t2, products AS t3 WHERE t2.mem_id = t1.mem_id AND t3.vendors_id = t1.vendors_id GROUP BY t1.vendors_id;

So, all of the vendors that have zero products are being left out of the results. Does anyone know if it's possible to achieve this without using a temp table?

Updating Table 2 Table
I would like to update a mysql table1 field4 where id 12 from table2 field5 where id is 14.

Update One Table Based On Count From Another
I heve two tables Publishers and Books.

Publishers has:
PublisherID
PublisherName
BookCount

Books has:
BookID
PublisherID
BookName.

I want a query that will update the BookCount field for every Publisher taking the number of books each one of them has in the Books table.

What would be the mySQL Update query for this?

Hope I have given enough information. I will gladly provide more.

Updating Table From File
I have a table and I need to update records in one column. There are 450 records in the table. I know I can insert records to table from file, but is there a way to update records from file?

Updating Table Privileges
Running MySQL 4.1.14 through Yahoo. When I access Privileges, I receive the following notice:

""Warning: Your privilege table structure seem to be older than this MySQL version!
Please run the script mysql_fix_privilege_tables that should be included in your MySQL server distribution to solve this problem!""

The Scripts folder does not include this file, and I do not know how to execute a fix for the above issue. Is there a way around this (i.e., uploading the mysql_fix_privilege_tables.sql script to run it, and if so, where can I obtain it?)

Updating Table With Datetime
I have a datetime field in a table and when I ran an update like so:

UPDATE myTable SET number=2 WHERE ID=50

I had the old datetime information in the table and that got
overwritten when I did the update. Now I am sure there is no way of
getting that back (yup, believe it or not I didn't do a backup) but
just a general question, should i have done the update like so:

UPDATE myTable SET number=2, mydatetimefield=mydatetimefield WHERE
ID=50

to keep the same information in the datetime field??

Updating A Mapping Table
I have a Publications table and a Themes table. There is also a mapping table for these tables as well.

When I input new records into Publications, my mapping does not get updated. When I delete, then the mapping table will get updated. (This is MySQL 4.x, so no trigger statements.)

My fear is that as I use the mapping table to display some information on a Web page, I will need to update that table "by hand" after I've entered a new record for Publications. Is there some method that I don't know of that will update my mapping table whenever I put in new records into Publications (esp. via a Web form)?

This is the setup for the mapping table: it has foreign keys on the primary key (ID) column of both Publications and Themes. That's it, nothing else in there.

Table Data Updating
I've heard that oracle will update data in a table when a specific event occurs and was curious if mySQL will do the same?
For my site I'm designing a comment section that will be attached to my news section. My database organization scheme will consist of two tables. One table that will hold all the news entries and another that holds all the comments. Thus, when browsing the news section visitors initially only access the news table, and once they click on the comments tab then they will access the comments table. Figured this was the best way to organize the data. However, I want the news table to contain the number of comments that exist for that news-section so that the count can be displayed.
My question is how can I make the news table update its data column containing the count for comments when the comments table recieves an update? Is this possible at all in mySQL? If there is a resource someone could point me in let me know, or if anyone has suggestions of a type of hack that would suffice as well

Match Rows In Table B With Rows In Table A
How do I structure a query to match rows in table B with rows in table A where column in B contains strings that contain data from column in A..

Example:

B.part = "abcdefg" matches A.part ="cde"

I cannot put literal in query.. it must be from column data..

It's easy to match rows where columns are equal, but I can't figure out how to get a match with "substring" as shown.

Table Creation Based On User Login
I'm trying to build a website that will allow the addition of users (w/ username, password, etc.).

That seems simple enough.

But is it possible to set something up (in PHP, for example) that will create a new table in the database for each new user?

Ex. John Smith signs up, is verified, and a PHP script (or Java, or whatever) creates a table specifically for him.

I know I'll need a master table of usernames, passwords, etc. These new tables would store certain user-specific data, such as preferences and other data the user might want to restrict access to.

I know I could store all of this information in a master table, but I'm trying to think ahead. Worst case scenario, if there are millions of users (unlikely, but not impossible), I'd hate to have all that data in one table, but if I have to, I can.

Update Based On Row Offset From Begining Of Table?
Is there a way to update a table row based on its offset from the begining of the table. I want to be able to update based on a rows position when its brought up when all rows in a table are selected. ie; select * from table.

Counting Levels On Adjacency Based Table
Does anyone know a single query that could successfully count the number of levels in a table based on the adjacency model?

By "number of levels", I mean the number of LEFT OUTER JOIN that needs to be used in a query such like this one :


SELECT
level0.cat_ID AS level0_ID, level0.cat_parent_ID AS level0_parent_ID, level0.cat_name AS level0_name,
level1.cat_ID AS level1_ID, level1.cat_parent_ID AS level1_parent_ID, level1.cat_name AS level1_name,
level2.cat_ID AS level2_ID, level2.cat_parent_ID AS level2_parent_ID, level2.cat_name AS level2_name,
level3.cat_ID AS level3_ID, level3.cat_parent_ID AS level3_parent_ID, level3.cat_name AS level3_name
FROM ecom_categories AS level0
LEFT OUTER JOIN ecom_categories AS level1 ON level1.cat_parent_ID = level0.cat_ID
LEFT OUTER JOIN ecom_categories AS level2 ON level2.cat_parent_ID = level1.cat_ID
LEFT OUTER JOIN ecom_categories AS level3 ON level3.cat_parent_ID = level2.cat_ID
WHERE level0.cat_parent_ID IS NULL
ORDER BY level0_name, level1_name, level2_name, level3_name

List Available Items Based On Prerequisite Table
I'm trying to develop such a scheme:

TABLE Prerequisites
PrerequsiteID (FK to Upgrades table; states a prerequisite for UpgradeID in the other column)
UpgradeID (FK to Upgrades table as well)

TABLE BuildingUpgrades
BuildingID (FK to Buildings table)
UpgradeID (FK to Upgrades table; states what Upgrade Building already has)

So it's a Building -> Building_Has_Upgrades -> Upgrades -> Upgrades_Have_Prerequisites thing (Building has 1..n Upgrades, Upgrade has 1..n prerequisites). In order for Building B to have an Upgrade U, that Building B has to have all the Upgrades which are required to have Upgrade U.

What I want to do is to list all buildings with all upgrades available for them. I've been trying for almost whole day to solve this issue with different inner, left and right joins, subqueries and what not but I can't really do it in a clean way.

The only working thing is a query, which I am ashamed of because it seems like a real waste of CPU time to me:

SELECT BUPG.BuildingID, PRE.UpgradeID, COUNT(PRE.PrerequisiteID)
FROM BuildingUpgrades BUPG
JOIN Prerequisites PRE ON BUPG.UpgradeID = PRE.PrerequisiteID
GROUP BY BUPG.BuildingID, BUPG.UpgradeID
HAVING COUNT(PRE.PrerequisiteID) =
(
SELECT COUNT(PrerequisiteID)
FROM Prerequisites
WHERE UpgradeID = PRE.UpgradeID
GROUP BY UpgradeID
)

What it basically does is takes all the available Upgrades, counts prerequisites that have been met by the building and checks if it's equal to the number of all prerequisites for that Upgrade. And it works but I still think there is a much better way to do it.

Updating A Table To Increment Values
Question, if I want to update all values in a certain column to increment by one, what statement could I use? In quasi-MySQL, this is my pseudocode:

UPDATE table SET fields=[previous_val+1] where [previous_val]>[my_val]

Or do I HAVE to run a SELECT query, increment the value, and THEN Update it?

I was just thinking there'd be an easier way.

Updating Table After Doing Multiple INSERT
I'm currently trying to do the following :

INSERT INTO sometable (userID,otherstuff) select ....blah blah ORDER BY RAND() LIMIT 10;

So I do that to get 10 random entries which works fine, however is there an easy way to then say...

For each of the 10 random userID's just inserted update another-field in another table with matching userID to the ones just inserted?

Table Locking When Updating From DataSet?
I have a bunch of code that updates tables from a VB.Net DataSets.

The original code updated Access2000 tables, I migrated the MDBs to MySql and have converted the data adaptors and command builders to MySqlClient statements.

Does anyone have any code examples to to the table locking using DataSets???


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