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




Incrementing Rows That May Not Exist


I'm sure there's a very simple solution to this, I just haven't been able to find one I understand yet.

I have a table with 3 columns, the first two are used as an index, and the third is a counter. So far so good:




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Joins To Rows That Don't Exist
I want to join two tables together, but if the secondary table doesn't have a row that matches, I want the primary table's row to still be returned, with the values for the secondary row being their default values. How do I accomplish that?

For example:

if I have two tables:

t1: defaults:(a=0,b=0)
+---+---+
| a | b |
+---+---+
| 1 | 3 |
| 2 | 4 |
+---+---+

t2: defaults:(a=0,c=0)
+---+---+
| a | c |
+---+---+
| 1 | 7 |
| 3 | 8 |
+---+---+

I want to execute a query like:
SELECT t1.a,t1.b,t2.c FROM t1 JOIN t2 USING(a)

But I want the result set to be
+---+---+---+
| a | b | c |
+---+---+---+
| 1 | 3 | 7 |
| 2 | 4 | 0 |
+---+---+---+

Selecting Rows From One Table With A Key That Doesn't Exist In Another.
I'm trying to select rows from one table that does not have a key in another table.

For instance:

I have a hospital table with two columns, id and name.

I have a patients table with three columns, id, name, and locationid.

Now I want to find those hospitals that have no patients. So I want to get those hospitals whos id does not equal any of the locationid's in the patients table.

Why Does The Slow Query Log Show More Rows Than Exist?
# Time: 070528 17:14:57
# User@Host: counter[counter] @ localhost []
# Query_time: 3 Lock_time: 0 Rows_sent: 7 Rows_examined: 120647
SELECT SQL_CACHE `webpageUrl`, `webpageName`, COUNT(*) AS `count`, (COUNT(*) / (SELECT COUNT(*) FROM _1_log)) AS `pct` FROM _1_log GROUP BY `webpageUrl` ORDER BY `count` DESC LIMIT 7;

mysql> select count(*) from _1_log;
+----------+
| count(*) |
+----------+
| 111824 |
+----------+
1 row in set (0.00 sec)

What Query To Check If Any Rows Exist Satisfying WHERE Clause?
I'm looking for a query that will check if any rows exists in a table according to a WHERE condition. I know I can use COUNT(*) but then mysql will do unnecessary task of counting all the rows whereas I just need true or false. So far I did this:

SELECT COUNT(*) AS exists FROM mytable WHERE ...
Sometimes I just select the first row and check later in php how many rows have been returned:

SELECT some_col FROM mytable WHERE ... LIMIT 1
But I cannot do this check (or can I?) in sql alone and I have problems when I want to use this in a subquery, for example:

SELECT id,
name,
(SELECT COUNT(*) FROM mytable WHERE ...) AS exists
FROM othertable
WHERE surname='xxx'
Can I do the same without using COUNT(*)? I would like a query that returns 0 or NULL if no rows were found, or 1 (or some other value) if 1 or more rows were found.

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

Incrementing A Value By 1
Is there a way to increment a value by one without using AUTO_INCREMENT and using only one query?

Incrementing A DB Value With SQL
I have a lookup table for articles that holds a sequence value in the sequence field.

When a user adds a new article, or updates an existing one, and enters a sequence number that is already in the table, I want all records that are greater than and equal to the entered sequence number to increase by 1 to maintain order.

I think I can figure out the rest from there once I can decipher the syntax needed to re-order my records.

Time Incrementing
I want to create a temporary table/view which will contain the times between two given times (incremented, say every 15 or 30 mins).


For example, I have the main table like this:

+---------------------+
¦ start¦ end ¦
+---------------------+
¦ 12:00:00 ¦ 13:30:00 ¦
+---------------------+
I want to output the incremented times into a temp table/view like this:

+----------+
¦ times¦
+----------+
¦ 12:00:00 ¦
¦ 12:30:00 ¦
¦ 13:00:00 ¦
¦ 13:30:00 ¦
+----------+


Incrementing Table Name
Is it possible to increment the table name by 1 each time a form is filled out e.g. 1st table name called "1" so the next table will be called "2" and the tables have to contain the same fields. Can this be done in PHP or MySQL?

Auto Incrementing
I am trying to make my own auto_increment for some tables as the ID's
have a string prefix in front of them. For example:

- customer table has the prefix CUS,
- employee table has the prefix EMP,
- item table has different prefixes like WB, WC, TFB, etc...

The difficulty i am having is finding the last inserted row for that
table. When I use the following SQL statement I don't get what i would
expect since MAX() orders them as strings and not numbers.

SELECT MAX(ITEMID) FROM Item WHERE ITEMID LIKE "TFB%";

If i was to run this query on the Item table which has the following
ID's:

WB0, WB1, WB2,...TFB0, TFB1,...TFB100, TFB101

The result that i would get is: TBF99 where i should be getting TFB101
!

I have tried everything from BINARY casting, using ORDER BY to
SUBSTRING but they all order the same way.

I.E TFB0, TFB1, TFB100, TFB101, TFB2, TFB20, TFB21,...TFB99

Is there a quicker way to auto increment with a prefix in mysql or
not?

Incrementing A Value In A Field
i want to update a value in a database.

i would normally read the value out of the database, assign to a variable,
then to $variable=$variable++ then use an update statement to set the new
value in the table..is there an easier way to increase a fields value by one in a single query?

Auto Incrementing
Can I put something in a SELECT statement that adds a new value for me for every row, preferrably starting at some particular value.

What I mean is, normally, you say:
CODE> SELECT word FROM words WHERE word LIKE 'a%';
+------+
| word |
+------+
| a    |
| aa   |
| aaa  |
+------+

Simple Incrementing
I have a field within my mysql database, this field, ContractNo, is the primary key. I have auto-increment set up to run on this field. However, it only starts from 0. The field is of type int. The value I wish to start the increment from is 24001000. Is it possible to assign this value as a starter value for my field to increment +1 everytime. I'm using navicat and everytime I place 24000000 as the default value, it always reverts it back to being blank.

Auto Incrementing
I am trying to make my own auto_increment for some tables as the ID's
have a string prefix in front of them. For example:
- customer table has the prefix CUS,
- employee table has the prefix EMP,
- item table has different prefixes like WB, WC, TFB, etc...

The difficulty i am having is finding the last inserted row for that
table. When I use the following SQL statement I don't get what i would
expect since MAX() orders them as strings and not numbers.

SELECT MAX(ITEMID) FROM Item WHERE ITEMID LIKE "TFB%";

If i was to run this query on the Item table which has the following
ID's:

WB0, WB1, WB2,...TFB0, TFB1,...TFB100, TFB101

The result that i would get is: TBF99 where i should be getting TFB101
!

I have tried everything from BINARY casting, using ORDER BY to
SUBSTRING but they all order the same way.

I.E TFB0, TFB1, TFB100, TFB101, TFB2, TFB20, TFB21,...TFB99

Is there a quicker way to auto increment with a prefix in mysql or
not?

Incrementing A Field
What is the best way to increment a field value by 1? Is there anything like
UPDATE mytable SET this_field = this_field++

Updating/incrementing Numbers
I am trying to systematically increment an "id" column of numbers in my table. Is there a query I could construct that I could cycle thru my "id" column, starting with a specific "id", and increment it and all the "id" records below it?

Starting Defualt Value For Auto-incrementing Primary Keys
I'm creating a table of users and each user ID should be at least 1000. For example, the very first user that registers is 1000 by default and then auto-increments on for subsequent users that register.

I use phpMyAdmin and tried changing the default of this auto-incrementing non-null, ID primary field but to no effect. The query was:

ALTER TABLE `site_users`.`users` CHANGE `UID` `UID` INT(80) UNSIGNED DEFAULT '1000' NOT NULL AUTO_INCREMENT

It did absolutely nothing to the default value

Select Where Exist
I have this tables:

category (id,name)
message (id,text,category_id)

I need a query like this :

insert into message set text='mytext',cid='$cid' where "cid exist in category"

I need some thing like this "cid exist in category"

Does The Table Exist
iam developing a servlet for accessing a database (iam using MySql database),
and iam wondering, how do i know if i have a certain table in thr database or not!!!
i mean how can i check if i have a certain table in the database!!! abf if dont have it, what is the error msg that i receive, so i can handel the situation !

Function Abs Doesn't Exist
I nstalled a mysql 5.0 Database on one of my servers but I receive the following error when I want to use a function from MySQL.

create view myView AS
select DATA,TIMED from myTable where ( abs (1138612032902 - myTable.TIMED)*11) >10 ;

And I receive :
ERROR 1305 (42000): FUNCTION MYDB.abs does not exist

I want to know if somebody has faced this error and I appreciate any solutions for this problem.

Add Index If It Doesn't Already Exist...
I need to add indexes to various tables on multiple databases. I'd like the script that does that to run without errors if some of those indexes already exist. How can I use 'IF NOT EXISTS' to create indexes?

I can't get IF NOT EXISTS to work with either of these:

ALTER TABLE la add index la_subclass_idx ( `user_id` );

or using

CREATE INDEX la_subclass_idx ON la ('user_id);

Record Exist
I'd like to get run a query which ask for a record (according to the ID), if it exists, it should return a 1 plus empty string, if not, a 0 plus data:

T1:
ID | data
1 | 'bla blo'
3 | 'bla bli'

wished result for ID = 1: [1, 'bla blo']
wished result for ID = 2 (which doesn't exist): [0, '']

Record That Does Not Exist In B From A
I've got a table for realtors(call this table A), all listings. I've got another table(table B) that stores the unique keys from table A, as well as related data. Then if I add a record to table A, I need to update table B with the unique value added.
What if I don't know what the unique value was, what is the best way to take care of this problem?currently in place is an old script that was 'ok' at the start, but as items have come in, it's simply not efficient by any means.

The old script is basically: INSERT IGNORE INTO `B`(`2`) SELECT `2` FROM `A` WHERE [some conditions];

So, how do I get the one record that does not exist in B from A, without knowing the value of the unique?

Table Doesn't Exist ERROR
I'm getting a "Table doesn't exist" error. The name of the table is "sitesearch"
But the table does exist! Strange...

So I executed :

mysql
SHOW TABLES

...and used PHP var_dump() to output the array fetched. The var_dump() gave me this :

Selecting Ids From One Table That Don't Exist In Another
I have 2 tables, they are both linked together and my life would be so much easier if they were just one big table, but they're not They have a one-to-one relationship between them and I need to find out the records in table 1 which don't have corressponding values in table 2. How can I do this?

SELECT id FROM table1 WHERE id NOT IN table2
Will that do it?


How To Find A Field Exist Or Not? Plz Help.
I've two 2 tables video and audio where i need to get all the fields from table video and no fields from table audio. the two tables are having video_sid in video table and audio_sid in audio as common fields. If the video table has video_sid and its corresponding audio_sid doesn't exist then it is said to have only video information and vice versa. If video_sid and audio_sid having same values exist then it is said that video and audio information exist for say an item. So if i need only video information how can i join audio and video tables so that i get only video information(Video only items).I've tried as below but doesn't work.

SELECT * FROM VIDEO V JOIN AUDIO A ON (isnull(a.audio_sid)) WHERE VIDEO_TYPE='MPEG1'

Insert Or Update If Exist
what is the sql statement that can insert or update the record if it exist.



Its Returning A Value That Doesnt Exist
Okay here is the deal. I am running a query to find out if there is an ID in my table that has a case number that matches the one being submitted. If there isnt once its should step into an if statement that would submit a number of records. Otherwise it should jump to the else statement.

I the problem comes from: the query keeps returning "Record id#2" but there is no record matching the case number being submited from the form.

if( isset($_POST['Submit'])){ //Begin If statement logic
$resultcheck = mysql_query("SELECT * FROM submissions WHERE wfmcase = " . $_POST['wfmc']) or die(mysql_error()); //Query string to test if wfmcase was already submitted
echo "Sucess, form varibles have been passed.<br />";
echo "Resultcheck query results: $resultcheck <br />";

if ($resultcheck == ""){ //Checks to see if the query was empty.
echo "There are no duplicate case escalations pending. <br />";

I added the echo statement so that i could see how far it was getting through the script. It dies after printing the varible $resultcheck which gives "Record id#2". It never enters the 2nd if statement because for what ever reason the query has the "record #id2" in it... What is causing this? I have verfied that there is no case that matches the one coming from the form and i get the same error.

Delete If Table Exist
I would like to delete rows only if table exist to prevents errors.

Also I would like to add column only if it doesn't already exist.

EXIST / IN / And Subqueries Does Not Work
I have been trying to get this working for a while but with no use.  I consulted the manual and even the JDBC manual which was developed by Mysql and all say the same think.  Every time i try to use the phrase "EXIST" or "IN" or "NOT IN" or even using sub query, it fails telling me that i have a syntax error near .... (the above options).

I am using Java and employing the JDBC driver from Mysql.

The mysql server runs 3.2.3. I test all queries in Mysql Control Center (the one that i use to test my SQL statements) before deploying in code

Sample sql:

Check If Field Already Exist
How can I check if a field already exist in a table? If it doesn't exist I want
to add it with ALTER TABLE ADD...

1146 Table Db.1 Does Not Exist..
Create a table in MySQL v5 using MySQL Control Center. When I try to open it, it opens OK but complains that a table (db.1) does not exist. I KNOW it doesn't exist. I DON'T WANT it to exist. I frankly couldn't care too hoots about not finding a table that I don't want and doesn't exist, so WHY must MySQL insist on telling me a non-existant table doesn't exist?

How To Insert If A Value Does Not Exist And Select If It Does?
Basically, I am doing a users table with an ID and a name for now.

I want to create a stored function that returns the ID of a user and creates the user if it does not already exist.

The way I do it for now is:

Select the user record by name.
If we had one, return its ID.
If not, insert a new user record and return its ID.

But I am worried about concurrency. What if another thread runs the same function while this one is between steps 2 and 3? TWO user records would be created for the same user. That would be bad.

I added a UNIQUE index to the username, but this means that the stored function will just error in a case like this, instead of returning the already existing user. This is also undesirable.

Finding Out If A Record Already Exist?
How do i find out if a record already exists in my data base,

like if it exists then
send me an error,
else
continue with adding records?

the code i have so far for pulling a records in loop:

$result = mysql_query('SELECT username FROM accounts');

while ($rows = mysql_fetch_array($result))
{

$user=$rows[1];

echo "user: $user<br>";

}

Temporary Table Does Not Exist
I've had this code running for over a year and now, all of a sudden, it no longer works.
I'm using PHP and MySQL 3.23.58 which my host provides. Code:

Does Table Exist Code?
I ran across this code to check if a table exists. I'm thinking there has to be a better way...maybe something like DoesTableExist("MyTable") = true or false.

Comments?

global $exists;
$exists = 0;
$dataset = mysql_query('SHOW TABLES') ;
while( $row = mysql_fetch_row($dataset) )
{
if ( $row[0] == "mos_tbd_tags" ) {
$exists = 1;
break;
}
}

Can A Composite Key Exist As A New Column?
I am trying to create a composite key in a table with two fields but I want to create a separate column which should be the combination of the 2 fields and should have some name to be worked with. Is this possible?

My query:

Delete File If Exist
I often create excel file from mysql in my local windows machine. I use

select last_name from mytable into outfile 'temp.xls';

the 1st time run is ok. the 2nd time run, it says file is already exist. how to write a script to find if the file exsit, then delete and run my select to create a new excel file?

Return ID If Record Already Exist
I looked everywhere (Google, manual, etc.) but can't find an answer to this
question.

If I do a "INSERT IGNORE INTO" query into a UNIQUE field and the word I'm
trying to insert already exists, can I get the ID of that existing record
returned so I can use it in the rest of the query?

Create User If Not Exist
I have a table of userids/usernames and another table which has data about games consisting of the users. What I want to do is to automatically add a user if they don't already exist in the table. I do this now:


Code:

INSERT INTO dkblue ( g_id , g_buyin , g_userid , g_finish , g_payout )

VALUES ( $gameid , $buyin ,

( select u_userid from usernames where u_name = '$value' )

, $key , $payouts[$key] )



As you can see, the value for g_userid is retrieved from the subquery. But this obviously does not work when the user does not exist. Is there a way to do this in a query or should I make sure all users exist on the PHP end before doing this ? I have just started trying to use subqueries and this one has me stumped.

Insert When Entry Is Not Exist
I want to be able to insert the new entry if the old entry not exist. Do i need to do the select then insert? Is there a better way to do it for faster & large database?


Code:


$query = "select count(*) as itisexist from AA where BB='$var'";
$result = mysql_query($query);
$line = mysql_fetch_array($result, MYSQL_ASSOC)
if ($line['itisexist'] == 0 ) {
$query = "insert into AA set BB='$var'";
mysql_query($query);
}

Mysql Database Doesn't Exist
I just tried downloading and installing mysql plenty of time. I tried
installing the "no-install" version and the other binary using
setup.exe. However, in both cases I just don't seem to have a mysql
database. I only see test.
If I go to C:mysqldatamysql I see bunch of files. However, if I log
into mysql and run "show databases;" I only see test. Also inside
WinMySQLAdmin under the databases tab I only see test.
I just want to do a new install, remove the anonymous logins like
every beginner tutorial suggests. However, I can not even find the
mysql database.

Find Field Exist
I've two 2 tables video and audio where i need to get all the fields from table video and no fields from table audio. the two tables are having video_sid in video table and audio_sid in audio as common fields. If the video table has video_sid and its corresponding audio_sid doesn't exist then it is said to have only video information and vice versa. If video_sid and audio_sid having same values exist then it is said that video and audio information exist for say an item. So if i need only video information how can i join audio and video tables so that i get only video information(Video only items).I've tried as below but doesn't work.Code:

SELECT * FROM VIDEO V JOIN AUDIO A ON (isnull(a.audio_sid)) WHERE VIDEO_TYPE='MPEG1';

Data Exist 52 Weeks From Today?
I have a database which has the date column. I am having trouble to come out with a query that can select the data which exists 52 weeks from today.

Query Based On 'does Not Exist' Condition
Let's say I have a table called 'forumtopics' with a field representing the topic author's username. I then have another table called 'ignorelist' which has two fields; one is an account number and the other a reference to the aforementioned author. There can be many ignored authors for any one account.

For any given account number, I'd like all the rows from the forumtopics table where there is no match for (account, author) held in the ignorelist table. Obviously it's easy to check for existence but can the opposite be done?

I run MySQL 4.0.17.

Query Based On 'does Not Exist' Condition
Let's say I have a table called 'forumtopics' that contains a field representing the topic's author. I then have another table called 'ignorelist' which has two fields; one represents another user and the other a reference to the aforementioned author. There can be many ignored authors for any one user.

For any given user, I'd like all the rows from the forumtopics table where there is no match for (user, author) held in the ignorelist table. Obviously it's easy to check for existence, but can the opposite be done in a single query?

I run MySQL 4.0.17.

SQL Server Does Not Exist Or Access Denied
When I try to access MySQL Database, I get this message. I think that I have the wrong pipe name for my SQL Server. But I am not sure how I find that out.

Update Record, Insert New If Doesn't Exist
I have a table that contains a list of parts used in a repair. The table contains foreign keys to the part and job concerned. it also contains data of time taken and status.

This data is read into a gui and the user can update the time taken and status. The user can also insert new parts in the gui.

is it possible to write an sql statement that will update the existing records and insert new ones if none already exist?

at the moment I'm having to try and update each record one, at a time and check the number of rows modified, if zero then insert a new record. all of which is done within the application. It works but doesn't seem very elogent...

Insert No Duplicates And Only If Not Already Exist In Other Table
is there a way to combine these two querie in one query?

I want to do this both:

SELECT *
FROM inventimport WHERE PC_volgnr NOT IN (SELECT dev_volgnr FROM dev) AND PC_volgnr <> 'geen pc aan' Order by inv_id

AND

SELECT DISTINCT PC_volgnr
FROM inventimport


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