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




Insert Values Only If They Do Not Already Exist In Table


I want to insert some values from one table (A) into another table (b). However there are some values in table A which exist two times in table A. I only want to insert values one time. So If a certain field value also exist in some other row (same fieldname) then I don't want to insert it twice. It doesn't matter which of the two rows will be inserted.

Can this be done with MySQL? Maybe with some Control Flow Functions?




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
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

INSERT Values From One Table To Another
In table A i have a.id and name and in table B, i have b.id, a.id(FK) and owns.

Table A
--------------
a.id | name |
--------------
12 | James |
13 | Paul |
14 | Tom |
15 | Andy |


Table B
--------------

b.id | a.id | owns |
--------------------
1 | 12 | Car |
2 | 12 | Bike |
3 | 13 | PC |

Now what i want is to add two new names to table A which will be Tom and Andy and have the same data in table B for Tom and Andy with just different b.id (PK).

How can i insert this new data in table B using insert?

Query To Insert 2 Foreign Key Values In Table
I want to insert 2 foreign key values along with some other value into table ....

INSERT INTO Table (vars) VALUES(vals)
I am trying to use the following command:
INSERT INTO sr_main (originator,symreq) VALUES (A.Person,269);

Whenever I enter the command above I get the following error:
ERROR 1054 (42S22): Unknown column 'A.Person' in 'field list'

I am confused because the error refers to my _value_ 'A.Person' as a column!? Do string values need to be surrounded with quote marks of some type? I have already tried the obvious (to me) quote markers, e.g. ", '

The data is accepted if I use this command:
INSERT INTO sr_main (originator) VALUES (269);

I actually have a lot more fields and values than shown, and ideally would like to use the command type:

INSERT INTO tablename (field1,field2,field3) VALUES (1,2,3)

Code:

Insert Table Values From Another Table
I have two tables: Users and metadata

Users:
id
userid
username

Metadata:
id
userid
value

I would like to extract a list of the userid's from the users table and enter them into the metadata table, with an additional value.

Example:
I want to take all of the userid's from the User table and insert them into the Metadata table, and make the value="one" for each entry into the Metadata table.

Insert Or Update If Exist
what is the sql statement that can insert or update the record if it 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.

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);
}

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 Multiple Fails Completely If Any Duplicates Exist
I've been having some problems with database performance... Several
threads are constantly attempting INSERTs of new records into a large
table - that is hundreds of thousands of records -large by my account
:-) The table has a VARCHAR field tagged as UNIQUE and inserts are
kind of slow. i'm relying on the INSERT to fail on duplicates, i'm
not performing any checking before i attempt the INSERT (i figured an
additional SELECT would slow things even more - but any advice to the
contrary would be appreciated).

While these back end threads are constantly banging away with their
INSERTS, front end users are hitting the DB with searches. so i end
up with several threads simultaneously attempting very expensive DB
operations. the result is that the front end that users see is
DREADFULLY slow.

My proposed speedup is to modify the behavior of the backend threads
so that they don't constantly attempt INSERTS of single entries, but
build up a hashtable of local entries and at some interval, attempt a
multiple insert something like:

INSERT INTO table (col1,col2,col3 VALUES (x1,y1,z1), (x2,y2,z2)....

While i do expect to take a big hit when these multiple inserts
launch, in the time between, i expect front end performance to be
significantly improved.

The problem with this situation is that the multiple insert may
contain one or more new entries which will cause duplicates on my
table's UNIQUE VARCHAR field. I would like to have duplicates ignored
on insert, but have all newly unique entries be added. Sadly, from
what i've seen, once a duplicate violation for any of the new entries
is found, the call fails, leaving my newly UNIQUE entries NOT ADDED.
Is there any way to get the call to work as i want? Doing many single
row inserts sounds like it'll be much slower (judging from what i've
read) so i'd rather not resort to that.

I don't have a ton of DB experience (which may be obvious) so if i've
overlooked something simple please let me know. If there's a better
way to improve performance other than these multiple inserts, that
would be nice to know about too. Thanks for any insight,suggestions,
etc...

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

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 !

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?


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.

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?

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;
}
}

Error 1146 Table Doesn't Exist
I made a backup of my db with 11 tables. I made some tests with the original tables, like delete data from some. After the tests I copied and pasted the backup to the original place. Now when I command: use mydatabase; Mysql goes ok. When I command: show tables; Mysql shows me the eleven tables in the db. But when I command:

select * from my table; Mysql returns to me the following message ERROR 1146 (42S02):

Table 'mydatabase.mytable' doesn't exist
What can I do to fix the problem?

Select Timestamp That Doesn't Exist In Other Table
Some of you probably know this trick to select rows from one table with an ID value that doesn't exist in another table:

mysql> SELECT table1.* FROM table1
-> LEFT JOIN table2 ON table1.id=table2.id
-> WHERE table2.id IS NULL;

But now take look at this particular situation:

CREATE TABLE `table1` (
`id` int(11) NOT NULL auto_increment,
`data` varchar(255) NOT NULL default '',
`created` timestamp(14),
PRIMARY KEY (`id`)
);

Same goes for table 2.
Now this is my problem: how can i select rows from table 1 with a timestamp `created` that doesn't exist in table 2? the IS NULL trick doesn't seem to work. I guess that is because a timestamp can never be null.

Table Doesn't Exist After Renaming Database
I have renamed my database from songsdb to songs by renaming the folder under MySQLMySQL Server 5.0datasongsdb to songs (stopped the server before doing so). Now when I restart, I see songs database, show tables shows all tables, but desc command gives error: ERROR 1146 (42S02): Table 'songs.djs' doesn't exist!

Whatelse am I to change to recognize these tables? I'm using 5.0.16-nt version on Windows XP.

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.

Only Showing Records That Do Not Exist In Another Table
How do I show a listing of all records within one table that do not exist within a second table?

For example:

Table A
----------
apple
orange
pineapple
banana

Table B
----------
orange
cherry
lime
banana

I want all records in A that do not exist within B to show. thus I should have the results of:

apple
pineapple

What would my sql statement be if my column name was "fruit"?

Error 1146: Table Does Not Exist
OS XP Pro SP2
MYSQL Ver: 5.0.0-alpha nt

Whenever I view a table or run a query in the Control Center (0.9.4-beta) I
get the following error:

[ShipNet] ERROR 1146: Table 'shipnet.1' doesn't exist

table shipnet.1 indeed does not exist but I can't understand why it's
looking for it. Any ideas?

FYI coincidently shipnet1 is the name of my computer.

Table 'mysql.host' Doesn't Exist
Working with mySQL 3.23.58 on Linux, I get this error when trying to start mysqld:
--------------------
060716 03:07:21  mysqld started
060716 03:07:21  /usr/local/mysql/libexec/mysqld: Table 'mysql.host' doesn't exist
060716 03:07:21  mysqld ended
---------------------

This Linux machine has been working ok for months, and it stopped suddenly.

I don't've any idea about how to fix it, and I don't find any '/etc/my.conf' file
into this machine. The install directory is '/usr/local/mysql'.

Table 'mysql.host' Doesn't Exist
Working with mySQL 3.23.58 on Linux, I get this error when trying to start mysqld:
--------------------
060716 03:07:21 mysqld started
060716 03:07:21 /usr/local/mysql/libexec/mysqld: Table 'mysql.host' doesn't exist
060716 03:07:21 mysqld ended
---------------------

This Linux machine has been working ok for months, and it stopped suddenly.

I don't've any idea about how to fix it, and I don't find any '/etc/my.conf' file
into this machine. The install directory is '/usr/local/mysql'.

Table 'test.event' Doesn't Exist
I'm evaluating MySQL 5.0.37-community-nt MySQL Community Edition (GPL).
For some reason I get this error. I don't recall doing anything in particular to cause this to happen. I can see the table in with the show tables; command. However, I can't select from it, insert into it or drop the table.
Can anyone tell me what caused this and how to correct it?

If Record Exist In 2 Tables, Use Column Of Table B
I have 2 tables A and B...
Table A: A_id, field1, field2, ..., status
Table B: B_id, A_id,..., status

I need to select all info from table A. And if a record exist in table B, i need to use the status value of that table instead of the one in table A.

Im not sure how to do it...with EXISTS or CASE?

Error 1146 - Table Mysql.1 Does Not Exist
I installed Mysql 5.x fine no problem and everything works , except when I try to do table mgmt in the Mysql control centre, eg delete rows from a table using the mouse. I invariably get this

error: 1146 Table 'mysql.1' does not exist

I think '1' is a temporary table that some setting is preventing me from using. Does anyone know what to change?

#1146 - Table 'inhous1_demo1.Admins' Doesn't Exist
i have table 'admins' in database. when i execute query like----->

-->SELECT *FROM `admins`;
i got result.
but
when i write query like---->
---> SELECT *FROM `Admins`;
i got error #1146 - Table 'inhous1_demo1.Admins' doesn't exist .

Mysql Table Doed Not Exist Problem
I am trying to "select" from a mysql table called "quiz".

I can execute the query successfully from command prompt.
select * from quiz;

but using JDBC, I am getting error
Table 'mysql.quiz' doesn't exist

Can anyone tell me why it is accessing "mysql.quiz" instead of "quiz".
what should i do now to tell mysql to look into quiz instead of "mysql.quiz".

How To Randomly Insert Values?
Is there a statement that can randomly insert values into certain fields.

For example let's say I have 1000 records and I want to randomly insert the values 10, 20, 30 into certain fields.

INSERT Values From SELECT
This works: INSERT INTO content (group_id) SELECT max(id)+1 FROM content;

But how do I enter into more than one field?

This doesn't work.

INSERT INTO content (group_id, content_id) (SELECT max(id)+1 FROM content), 55;
OR
INSERT INTO content (group_id, content_id) VALUES ((SELECT max(id)+1 FROM content), 11);

You can't specify target table 'content' for update in FROM clause

Insert With Both Values And Select
I need to insert multiple values in a table I use an insertstatement like this one

insert into table(name, jobID) select 'Jon', id from jobs where name = 'programmer';

However, if I have a value before the condition like
insert into table (jobID, name) select id from jobs where name='programmer', 'jon2';

it does not work and I need such a statement to work cuz I get different data with a lot of fields and I do not know in advance which will be fields with have direct values and hich will ghave to get data from other tables

Insert A String Of Values
as you will see iam new to php/mysql and desparately require some help. My problem is as follows -
i need to enter a string of values from a list or selection of checkboxes into ONE field. Iam using dreamweaver and although it has the option for multiple entries it only inputs the first selected in a list. all i need it to do is be able to input for example beach facilities
- toilets, slipway, lifeguard
into one field from a list of facilities. i don't need to separate them at a later date as i will display them just as above. Your help will be greatly appreciated as it is a reg charity based website for marine wildlife that iam trying to construct.

INSERT (cols) VALUES (...), (...)
INSERT INTO labResults (labType, labValueAM, labValuePM, retest, labTest, sampleDate, RxNumber) VALUES ('saliva', '0.00', NULL, NULL, 'Estriol', '2006-02-24', '8888888') ON DUPLICATE KEY UPDATE (labType, labValueAM, labValuePM, retest, labTest, sampleDate, RxNumber) VALUES ('saliva', '0.00', NULL, NULL, 'Estriol', '2006-02-24', '8888888');

That's what I'm trying to do, but I get a syntax error. What's wrong?

ERROR 1146 (42S02): Table 'spnau_dev.spde_user' Doesn't Exist
I used the migration tools try to migrate tables. There are a table can't be create because of the constraint. I fixed it and create the table under the schema and then continue the migration. After migration completed and when I select, drop the table, I got this error. when I drop the schema, I also got the error.

ERROR 1146 (42S02): Table 'spnau_dev.spde_user' doesn't exist

This table is innodb type. we are using version 5.0.27-standard.

when I show table in the schema, I can see the table.

in the information_schema.table. I saw the table. But the information is all not right.

'', 'spnau_dev', 'spde_user', 'BASE TABLE', '', , '', , , , , , , , '', '', '', '', , '', 'Table 'spnau_dev.spde_user' doesn't exist'

Can someone help me on this ?

INSERT Values In Three Tables Using ID Column
how to insert values in different tables?

Table t1 got a column named "id" and this value should appear in t2.t1_id

In other words: How to fill all columns in all tables with one INSERT / UPDATE ?

t1

id bigint autoincrement
name varchar()
bla
bla


t1
id ....

How To Insert And Update Multiple Values In One Record
How do I insert and update multiple values in one record. e.g.

1. How do I insert "dogs,cats, snakes" in one record
2. If I have "dogs, cats, snakes" in one record and I want to update it and add 'pigs' to make it "dogs, cats, snakes, pigs", how do I do that?

Fatal Error: Can't Open Privilege Tables: Table 'mysql.host' Doesn't Exist
When I start the MySQL server it gets stopped immediately logging the following error.
050607 15:27:43 InnoDB: Started
050607 15:27:43 Fatal error: Can't open privilege tables: Table 'mysql.host' doesn't exist
050607 15:27:43 Aborting

050607 15:27:43 InnoDB: Starting shutdown...
050607 15:27:45 InnoDB: Shutdown completed

How To Insert New Records Based On Previous Record Values?
I have
TABLE:

year
value

It has for example,

year, code, vlaue
2007, 33, 4883
2006, 33, 4883
2007, 32, 4883
2006, 32, 4883
2008, 31, 4883
2007, 31, 4883
2006, 31, 4883

I want to insert new records for for 2008 for all codes that do not already have a record for 2008 and increase the value for the 2008 record by 3%.

My several attempts have led to this but which does not work.

UPDATE TABLE a
SET a.value = b.value * 1.05
WHERE b.year = 2007
AND code NOT IN
(SELECT code
FROM TABLE b
WHERE year =2008
AND value !=0)

Table Does Not Exist (was "Database Error")
Database error: Invalid SQL: update sponsors set status=-1 where end_date<=&#55614;&#57158;-07-22'
MySQL Error: 1146 (Table 'chinese.sponsors' doesn't exist)
Session halted.

What does this mean ?

1 Simply Query Problem. Please Help With Insert Into 1 Table From Another Table
I have Table A that has some records already in and then I have Table B that does a few things and gets updated regularly.

With Table A, I want to get it updated every 8 hours or so with new data that has been inserted into Table B.

I will do this using the Cron.

But what would be the best insert query to use so that it does the process really quick.

The query that I have so far is:

Quote:

mysql_query("INSERT INTO table a (id, title, descrip) SELECT id, title, descrip FROM table b where app=1");

With the above query the id's match in both tables. But I only want the new records to be inserted into Table A where app=1 in Table B and the row is not already in Table A.

How can I add to the query so that it does this.

INSERTing Into A Table, With Values From Another Table
I'm programming a shopping cart application, where the products are categorized into different lines. I have a table that defines the different product lines, and now want to populate the product table.

However, the text file with the products in it, which I will use to populate the products table, uses the line NAME for each product, when I wish to use the line ID instead. To get the line ID, I would need to get the value from the line table.

My question is: is it possible to populate the products table with data from the products text file, as well as a column from the lines table?

That is, the INSERT (or LOAD DATA) statement will insert column values from the text file, but the line id from the lines table instead of the line name found in the file (WHERE line name = line name in the lines table).

I'm still not sure whether to use an INSERT, and write PHP code to go through the text file, or to use LOAD DATA for this task, because I don't know which statement would support what I'm looking for.



Update One Table Value With Values From Another Table
I am trying to update one table value with values from another table, and I cannot get it to work. What am I doing wrong?

This is my SQL-command:
UPDATE tabel1 SET tabel1.name=tabel2.name WHERE tabel1.ID=tabel2.ID

Inserting Values From 1 Table Into Another Table
I have 2 tables: A and B
Table A contains fields u, x and y
Table B contains fields u and z

Table A has all possible variations of u.
Table B has some of the varaiations of u in it.

My problem is that I'm trying to insert the z-values from Table B into Table A's y field and link them up based on the u-values.

I'm running into problems like truncating at row 0.

I've tried the following queries:

update TableA set y =(select TableB.z from TableB where TableA.u=TableB.u)

update TableA,TableB set TableA.y =(select TableB.z from TableB where TableA.u=TableB.u)

Insert New Rows With Qty Values From Existing Rows
I am trying to make all my products unique in my db.
Lets say I have a row with an id, it also has all relevant details about the product and it has a quantity value of 4.
What I would like to do is take the entire row and duplicate it by the number of the quantity field.
This would result in the same product 4 times instead of one product with qty of 4.
Reason, I am going to serialise all the products so that they each have unique barcode from the id field.
I will encounter the reverse issue when running an insert statement for inputting new data, i.e. insert a new row for each item depending on its qty value??

Add Values To Table
I have a table tblMailingList. It has 3 columns; Name, EmailAdd, AutoID.

I am using
mysql> INSERT INTO pet
-> VALUES ('name1','u@me.com');

but I am unsure as to what to do for the AutoID field. If I use the example given, the error message says that the number of fields is different.
How do I get this info into my table?

Update A Table With Values In Another
I have the following table

tableA
column_a
column_x
column_y
column_z

tableB
column_x
column_y
column_z

How do I update the rows of tableA that match rows of tableB (all rows
of tableB are unique)

What I want to acheive is a check against tableA.column_x with
tableB.column_x, if they match, then update the row in tableA.column_y
with the value of tableB.column_y and tableA.column_z with
tableB.column_z


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