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




Select All Records From One Table That Does Not Appear In Another Table


I need to select all records from tableA that does not appear in tableB. I am using the following query that does work but is very very slow. Is there anything i can do to speed up the query?

select tableA.ID, tableA.Name, tableA.Surname
from tableA where tableA.ID != ALL (select tableB.ID FROM tableB where tableB.status = 'inserted' or tableB.status= 'edited' or tableB.status = 'deleted' );

I have as example 6000 records in tableA and 2000 records in tableB. tableB is used to track which records have been inserted, edited or deleted from another system so the query should return all records that do not exist in the other system yet.

This query runs for about 3mins and just gets slower the more data there is.
Can anyone suggest anything that could make this a sub second response?




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
HOW TO: Select Only The Last 2 Records In A Table.
I'm not very good in mySQL but am trying to modify a script.
It has to do with a log table.
I want to retrieve the last 2 log records (if any) and if the last log
entries are the same as my current (to be) entry, simply update the time in
the last entry. But if not, simply insert the new entry.

My question is how to select the last two entries from the log table?

CREATE TABLE broadcast_log (
id mediumint(8) unsigned NOT NULL auto_increment,
time varchar(20) NOT NULL,
entry varchar(255) NOT NULL,
PRIMARY KEY (id)
);

Best Way To Select Records WITHOUT Relationship In Another Table?
I have a stock table and a stock_category_r table which is a relationship table between stock items (products) and stock categories (M:M relationship)

I need to select stock that is uncategorised. I.e Items that have not been related to ANY categories.

I was using this query with a subquery:

SELECT s.ID, s.code, s.name
FROM `stock` s WHERE s.ID NOT IN
(SELECT stockID FROM stock_category_r)
Just wondering if this was the most effecient way to find stock records that have no corresponding relationship in stock_catgegory_r ?
Do sub queries effect performance much?

My tables for this app have very few rows, but I'm interested in the best-practice theory


The table structure:


CREATE TABLE `stock` (
`ID` smallint(5) unsigned NOT NULL auto_increment,
`code` varchar(16) NOT NULL default '',
`name` varchar(40) NOT NULL default '',
`description` mediumtext NOT NULL,
`image` varchar(35) NOT NULL default '',
PRIMARY KEY (`ID`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;



CREATE TABLE `stock_category_r` (
`stockID` smallint(5) unsigned NOT NULL default Ɔ',
`categoryID` tinyint(3) unsigned NOT NULL default Ɔ',
PRIMARY KEY (`stockID`,`categoryID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

All Records From Table A - All Records From Table B - Join Alike Records
I am by no means a SQl Jedi as will be apparent by my question, but I
can usually figure out a select statement on my own. I have one today
though that really has me stumped. I am working in MySQlL 5.

In My first select statement I get all my records from Table B
SELECT
`table_A`.`ITEM`,
`table_A`.`DECSCRIPTION`,
`table_A`.`UM`,
`table_A`.`PHASE`,
`table_B`.`Qty`,
`table_B`.`Calc` as calculated
FROM
`table_A`
Inner Join `table_B` ON `req_itemlist`.`ITEM` = `table_B`.`ItemID`

In my second statement I get my records that match in this case phase
401 in Table B and all my Table A records for phase 401.

SELECT
`table_A`.`ITEM`,
`table_A`.`DECSCRIPTION`,
`table_A`.`UM`,
`table_A`.`PHASE`,
`table_B`.`Qty`,
`table_B`.`Calc` as calculated
FROM
`table_A`

Left Outer Join `table_B` ON `req_itemlist`.`ITEM` = `table_B`.`ItemID`
Where
table_A.PHASE In ('401' )

Now I need to combine the Data of both recordsets. I need EVERYTHING in
Table B, but I also need All Table A records that match the phase
selection....

Can I write this one query or do I need to use a Temp table?

Slow Select Using Count(distinct) In A Table Bigger Than 100000 Records
Recently I started using MYSQL in my enterprise. I made a table which has around 100000 records. The problems is that it is really slow.. Im trying to do a query in which I get the number of distinct users per day.

This is my query:

select date(startedDate) as mydate, count(distinct(Users)) as users from Mytable
group by mydate

It is really simple and it does it correctly but it takes one minute.. One minute is not too much time but i need to insert around 10 000 000 records and thats what worries me.....

Query Table A And Return Records Not Found In Table B.
Given table A and table B.  Table A is a master table and table B is a list of authority or reference which is fed by selecting records from table A (via an UI I wrote in PHP).

The interface is working fine but I am left with one problem.    If I need to edit my table of authority, the source table (table A) should return ONLY entries not previously selected.

That said, if the A.key is in B.key, records from table A matching B.key should be omitted.

I could do this by looping through the query results from table A and querying table B, if no match, show A.key.  This I think is a bit antiquated and possibly too involved.

Is there a joint query command I can use?

Finding All Records In One Table That Don't Have A Corresponding Record In Another Table
I have photo information stored in a table called pictures. One column is keyword.

Visitors to my site can search for photos by keyword.

I record search terms in another table called searches. Each search term is recorded, meaning there are duplicate search rows. This allows me to see easily the popularity of a search term.

Step 1. What query can I run to find all search terms that return no matching picture in the picture table.

I tried the following, but no luck:Quote:select term from searches left join pictures on term like keyword where picture_id is NULL

Copy Records From One Table To Another Table
What is the sql query in mysql which copies all records from one table to another table within a database...? and query that copies records from one table to another that belongs to a different database...

Trying Abort One Select Accessing One Table Locked By Lock Table.
I'd like to configure one time to abort one transaction that are accessing one table locked by lock table write command ex:

Transaction A
mysql> start transaction;
mysql> lock table mytable write;

After I'll start new transaction B (another connection)

mysql> start transaction;
mysql> select * from mytable;

It's will become long time to wait...

My transaction B never "die".

I tried to configure innodb_lock_wait_timeout=20 in my.ini without success,

Rights To Create Table, Select, Then Drop Table..
I have a need to get data from the db that requires me to=20

1) do a select and create a new table with the results=20
2) run a query against that new table=20
3) drop the new table=20

I have a script on my server that does this using the root account that has all on *.* for the db. It works fine.=20

I now want to get these results on a web page.=20 I want to create a new db user for my .php web page to use to connect to the db that only has the needed priviledges on that specific db to get the job done.=20

what priviledges do I need to give that user?=20

currently I have the following but the user can't even log into the db from the command line..=20

mysql> show grants for user;=20
+-----------------------------------------------------------------------
---------+=20
| Grants for user@% |=20
+-----------------------------------------------------------------------
---------+=20
| GRANT USAGE ON *.* TO 'user'@'%' IDENTIFIED BY PASSWORD
'6fe4c0ab2cf30ae3' |=20
| GRANT SELECT, INSERT, UPDATE, CREATE, DROP ON `db1`.* TO 'user'@'%' |=20
+-----------------------------------------------------------------------
---------+=20
2 rows in set (0.00 sec)=20

when I do a "show grants for user", what should I see to allow what I want?

SELECT From A Table Depending On A Result From Another Table
This may sound a bit weird so i'll explain:

I have three tables:

tbl1foobar
------------------
ididid
type enum('foo', 'bar')infoinfo
typeid

Now I want to get the info from either foo or bar depending on tbl1.type
Is it possible to do this in one select statement?

Table Design Question? House Table, Owner Table, Code Violations Table - Best Way?
Given the tables:

HOUSE
house_ID
address

OWNER
owner_ID
name
telephone...

HOUSE_OWNER_JOIN
?

CODE_VIOLATION_HISTORY
house_ID
violation_ID
violationStatement
...

My goal is to be able to track code violations of the house PER owner.

For example, I need to display a page that shows the current house with it's coe violations and a link to show the HOUSE's history of violation regardless of owner, Like:

House 1009283
Address
Past history (link to the following)

House History
2001-01-04 Owner: John Smith Code Violation: Gutter issue
1999-06-01 Owner: John Smith Code Violation: Faulty Steps
1998-03-02 Owner: Sam Spade Code Violation: Driveway carcks
1990-01-12 Owner: Keith Sledge Code Violation: Grass untidy


For the design of the HOUSE_OWNER_JOIN table, I thought of two ways I could go on this and this is where I need your help.

Option 1:
Have the HOUSE_OWNER_JOIN table keep dates so I can track the ownership changes that way:

HOUSE_OWNER_JOIN
houseID
ownerID
dateOwnershipBegan
dateOwnershipEnded

then I could look up all code violations by date and associate them with their rightful owner.

==================================================
Option 2:
Have the HOUSE_OWNER_JOIN table be the primary keeper of identity data by adding a new primary key and changing the CODE_VIOLATION_HISTORY table to reference that table by chaning the referencing key from house_ID to house_owner_ID:

HOUSE_OWNER_JOIN
house_owner_ID
houseID
ownerID
dateOwnershipBegan
dateOwnershipEnded

CODE_VIOLATION_HISTORY
house_owner_ID
violationStatement
...

Select All Elements In One Table That Do Not Appear In Another Table
Say that I have a table A with column colA and table B with colB.

How do I select all elements of colA in table A that are not in colB of table B?

How To Copy Records In One Table?
does anybody know how to copy a record within one
table? I am looking for some simple method similair to
INSERT INTO orders SELECT * FROM orders WHERE
Order_ID=256; Actually, this method does not work and
I can not believe that MySQL does not offer some
simple method how to do it. Keep in mind that I have a
60-field table. So, naming all fields is a pretty
tedius task.

Count Records In 2nd Table
Create a result set with all records from table A and counted related records in table ....

Limiting Table Records
Is there a way to limit the number of record in a table, for example i want 20 in my table, if a new one comes in then the oldest one just gets dropped.

Query To Get Records In One Table But Not In Another One.
I have this query that works but now I want to refine it so that it only selects records in the loaninfo table that do not have a record in the achtransfer table.  I not sure how to do that.  Here is the query I have now....

How To Copy Records In One Table?
does anybody know how to copy a record within one
table? I am looking for some simple method similair to
INSERT INTO orders SELECT * FROM orders WHERE
Order_ID=256; Actually, this method does not work and
I can not believe that MySQL does not offer some
simple method how to do it. Keep in mind that I have a
60-field table. So, naming all fields is a pretty
tedius task.

Inserting Records From Another Table
i am using the following SQL to insert records into Summary table from another table but i keep getting a syntax error.  When i run teh sqls individually, they work ok... any thought on how i can get this done?

INSERT INTO tSummary
(ssnumber,unitid,projectid,tenant_lname,tenant_fname)
VALUES(select ssnumber,unitid,projectid,tenant_lname, tenant_fname from tExternalData)

The error that i get follows:

[admin] ERROR 1064: You have an error in your SQL syntax near 'select ssnumber,unitid,projectid,tenant_lname, tenant_fname from tExternalData)' at line 3

Different Languages In Table Records
I wanted to add different language support for my application and for that i needed to add text in languages like Arabic and Hindi into the records in a table in my Mysql Database.

I tried simple copy paste in MySQL administrator but it did not recognize the characters..
how do i enable support for the language's character sets?

Moving Records From 1 Table To Another
Is there and easy SQL syntax to move or copy rows from 1 table to another?

I'm creating a temporary table and after matching duplicates, and deleting the duplicate rows, i want to move or copy the remaining rows into the permanent table.

Counting Sub-table Records
I need to write a SPROC that will be pulling information from several tables, altering formats, and inserting into new tables. The query is several hundred lines long. Most of the tables have a related index field.

What I need to do is use a few LEFT JOINs during the SELECT for one of the tables. I need to know, for this table, how many records from some of the other tables have matching Id numbers. I am having trouble figuring out the COUNT statement. Code:

Maximum Records In A Table
Is there a limit or design limit on the numbers of records a table can hold using mysql?

Joining Table Records
Migrated an MS Access database (which has linked/joined table records).

Reviewing the records within MySQL Query Browser, I noticed there's no obvious indication of the table records still being joined/linked; nor did I find a way to recreate them.

I need to know that a link exists before I begin coding PHP. (Which is also new to me.) Don't want to run into a problem with having the correct coding but the wrong answer based upon the lack of links.

Way To Duplicate Table And Its Records?
Is there a way in mySQL to duplicate a table? I want to copy a table's structure and all of its records, for testing purposes.

Joining Two Records From Same Table
I have a parent-child relationship in a single table, with permissions set on the parent object.

I want to query one child record, but grab the permissions from the parent object....

Posting Records To Table
Im building a PHP page where Im allowing visitors to input information using a online form.

With MySql

The table is got the first field primary (id)
1-8000 records

there are another 22 empty fields in this table.
year, color etc...

each (id) field is unique to a product model

Im asking how is it possible to post
multiple entries to the unique (id) field?

I would then be able to query the table and display entry after entry for the unique id field.

Update Records In Table
i have installed a mysql server, and i have a problem with import record in database.
the origine is a file txt or csv, the destination database contain also other records, and i must update the records into database

Help With Performance Of Table With 200k Records
My client is experiencing severe performance issues going through a sales process. the order/cart table has around 200,000 records and is modified as you move through the process. Performance for multiple item orders takes a minutes to refresh.

Their server version is 4.0 and the table has a primary index. (I am moving it to at least version 4.1)

It is running PHP as the scripting language and I am going through logs to see what's up there as well but the performance issues have been ongoing and getting worse so it leads me to believe it's a db issue.

Pull The Last 10 Records From A Transactions From A Table
I'm trying to pull the last 10 records from a transactions from a table using this query:

SELECT * FROM transactions ORDER BY timestamp DESC LIMIT 10

But I want to display the rows in ascending order by timestamp. I can't get the subquery below to work and not sure why:

SELECT *
FROM (SELECT *
FROM transactions
ORDER BY timestamp DESC
LIMIT 10)
ORDER BY timestamp ASC;

Copy Changed Records Into Same Table
Is there any way to select several records from one Table, and copy them back to same Table but with changed values of one field (for instance: values of Foreign key field)?
((records with original values needs to remain in Table))

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.

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"?

Combine Records Of A Column Of The Same Table
i have all my portal contents on the SQL Database in the following manner:

Node_id Contents
12 this the first page
12 welcome to the portal
12 this is some sample data
13 this the second page,
13 sample data

when a page is being loaded, depending on the node_id contents are retrieved and displayed. Now i need a query which would combine all records of the same Node_id (page) and display as one record.

Eg:
Node_id Contents
12 this the first page welcome to the portal this is...
13 this is the second page, sample data

Selecting The Correct Row In A Table Which Records Changes
I have an "employees" table which records which department each employee has worked in, and the date that each employee started working in their departments. Since it is possible for an employee to change departments, a single employee can have several records in this table. For example, consider the following history for Employee 42:
1. On Jan. 15, 2007, Employee 42 is hired to work in Department 21
2. On Feb. 1, 2007, Employee 42 changes departments to Department 5
3. On Feb. 14, 2007, Employee 42 changes departmets to Department 22
4. On Mar. 3, 2007, Employee 42 changes departments to Department 18

Then, Employee 42's records in the "employees" table would look like this:
CODEselect * from employees where employee_id = 42;

Cleaning Up MySQL Records In A Table
I transfered a mysql database to a new mysql server using a little software... Thing is, it put some garbage characters at the end of every record and it messes up when I try to echo the result in PhP.I'm looking for a way to remove the unwanted characters (or non-alphanumeric characters) in each record.Is there an easy way to do this ? I'm also using phpmyadmin, if it can be usefull.

How To Find Records That Are NOT Referenced In A Join Table?
Table structure...


CREATE TABLE category
(
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(40) NOT NULL
);
INSERT INTO category (id, name) VALUES
(1, 'CSS'),
(2, 'HTML'),
(3, 'XML'),
(4, 'Javascript'),
(5, 'PERL');

CREATE TABLE category_j_article
(
category_id TINYINT UNSIGNED NOT NULL,
article_id INT UNSIGNED NOT NULL,
PRIMARY KEY (category_id, article_id)
);

CREATE TABLE article
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(40) NOT NULL
);

Let's say I want to find all articles that aren't filed under multiple categories? For example, if I want to find articles that aren't filed under the CSS and HTML categories?

Cross Table Search For Orphaned Records
I have two tables in a databases. The tables are:

orders
devices

Orders table has a primary key order_id which auto-incs. Devices points to a single order via a field, associated_order_id which is an int.

I am trying to execute a query to return all devices that have an associated_order_id which doesnt acutally exist as a valid order_id in orders. I.E. Orphaned devices with no parent to an order.

Here is what I was thinking, but IT DOES NOT WORK. It returns thousands upon thousands of results.

SELECT devices.* FROM devices, orders WHERE devices.associated_order_id != orders.order_id

Move Records From 1 Table To Another And Including 1 Field
I've created a table called `temp` and I want to move all the rows in `temp` to `songs` based on:

`temp`.`title` -> `songs`.`title`
`temp`.`artist` -> `songs`.`artist`
`temp`.`catalog` -> `songs`.`catalog`
NOTHING -> `songs`.`userid`

There is no field in the temp table that has this value, i will need to insert it along with each record. How would I go about doing that, without looping through 1 query and inserting each as I go?

How Many Records Can A Single MySql Table Hold.
I have a mysql database running on Mysql version 3.23.53 on a Red Hat
Linux 7.2. In the database there is a single table with over 150,000
records. Unfortunately, the performance of that table is very poor,
comparing to other tables in the same database.

How Many Records Can A Single MySql Table Hold.
I have a mysql database running on Mysql version 3.23.53 on a Red Hat
Linux 7.2. In the database there is a single table with over 150,000
records. Unfortunately, the performance of that table is very poor,
comparing to other tables in the same database.

Mysql, Simple Table Join - How To Loop Through Records
I've been gradually learning and using PHP for about a year and I've now decided to start learning MySQL

I've got my first database up and running, and I can display records, edit/delete/search and sort records from that database. But I want to make things a bit more complicated and start making related tables.

I've decided to re-invent the wheel and make a very simple content management system for myself, just to see if I can.

I have a table called posts, which is what I enter my table content into, consisting of headline, creation date, post text and an id field.

I've also set up a table called comments which will allow users to add comments to my posts. In the comments table there's a field called id_post - which is the id of the post that the comment relates to in the posts table

I've already got my loop set up to loop through my posts records, but I'm confused about how I go through looping to get the comments records.

How do I do the loop?

I thought about doing an SQL query to the comments table nested inside my loop through my posts results

SELECT * FROM comments WHERE id_post='$id' ORDER BY stampcreate


But I assume this isn't the most efficient way of doing things....

Using A Query To Exclude Records From One Table, If The Field Value Exists In Another
I'm very new to SQL, and wondered if someone could help me out:

I am building a query which contains two tables. One table has details of everything everyone owns.

The other table is a list of things which people own, but that I don't want to see.

Is it possible to design the query so that I see all of what everyone owns, except the items listed in the other table?

Mysql Insert Records In The Middle Of Database Table
I have a table with field serial number(slno double).

I have data like this:
slno
-----
1
2
3
4

Now I want to insert a record between 3 and 4, so that the new record should have the number 5 . How to implement this? Same case with deleting a record also.

SELECT INNER JOIN Performance VS Single Table SELECT
I have designed my database using a somewhat oriented approach. Rows are objects, and different type of objects are in different tables, but since my objects share a common set of fields like ExpireDate, Archived, Draft, CreateDate, CreatorID, etc; I have an 'objects' table with these columns, and I have set up a foreign key in other tables where there is a need for a row-to-row integrity.

Now my question is, since I have to SELECT using INNER JOIN with object and the corresponding table, merely to filter out archived rows, I am wondering if I would be better off actually putting the common fields into each respective table and get rid of the 'objects' table altogether. I mean, is it more job for the server to actually JOIN the tables for each SELECT versus having a clean design with object oriented approach ?

How bad is my design, and what are the recommendations of experts who obviously were tempted to create an object oriented database design?

Select From First Table Where Id Is Not In Second Table
I have two tables. One is a backup of the other, but with slight changes in the fields.

I am trying to restore only the deleted rows of the table, by retreiving them from the backup.

I thought about something like:

Select * from backup_tbl Where id != ... then i don't know.

Update A Record Out Of 2 Duplicate Records Which Dont Have Primary Key In Mysql Table
how to update a record out of 2 duplicate records which dont have primary key in mysql table?

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

2 Table Select.
I have the following query and it erros out saying the select field name is ambigious. The tables are exactly the same. How would I go about fixing it?

I just want it to return the user_id if it returns a value for either table.


SELECT user_id FROM amt_users a, pro_users p WHERE `a.username` = '$username' AND `a.password` = '$password' OR `p.username` = '$username' AND `p.password` = '$password'

2-3 Table Select
I Have 3 tables
-----------------
person
ID
person_name

product
ID
product_name

person_review
ID
product_ID
person_ID
---------------

Basically I a person reviews a product, their ID and the products ID gets put into the person_review table. I want to be able to go through the person_review table, and see what products haven't been reviewed, and what products haven't been reviewed by 'x' user.

So far, this has gotten me, what products a specific person HAS reviewed, but I am unable to get which ones they haven't reviewed. Code:


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