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


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





How To Query Multiple Tables Based On Value Difference


I 5 tables all with equal columns,but with different values. Per example:

time_start,time_end,num_a,num_b,price etc.

How can I retrieve the values of all columns `price` between tableX and tableY where time_start in table Y is higher as a datetime than time_start in X.
So,the query is about finding the values of `price` between 2 dates in differnt tables.




View Complete Forum Thread with Replies

Related Forum Messages:
Query Based On Data Of 3 Tables
this is what I've been trying to implement:

I have, say, three tables.

One is a user table, with id, username, etc
Second is a question table with Question ID, Question, Category etc
And third is an "answers" table that keeps answers given by the users. It has the classic id key, and Question id and User Id columns.

What I want to do is this:
Select a random question of category 1 lets say from the questions table for which user X has no record of answering in the answers table.

View Replies !
Determining Which Table To Query Based On Data Within Tables
I have 2 tables:

default_categories
column 1: category_id
column 2: category_name
column 3: category_parent

custom_categories
column 1: custom_cat_id
column 2: custom_cat_name
column 3: custom_cat_parent

The custom_categories table won't necessarily have anything in it but if it does, I need to choose the data from the custom_categories table over the data from the default_categories table.

So if the default category has 3 rows with IDs | names:
123 | Dogs
456 | Cats
789 | Fish

And the custom category has 1 row with IDs | names:
456 | Very Cute Cats

I want my query of these 2 tables to produce the following IDs | names:
123 | Dogs
456 | Very Cute Cats
789 | Fish

I've tried joins like the one below but they aren't working because if there is no custom_cat_id, it won't give me the result for the default category_id.


MySQL
SELECT *
        FROM default_categories
        LEFT JOIN custom_categories ON category_id = custom_cat_id
        WHERE category_parent = ''
        AND custom_cat_parent = ''
        ORDER BY $order_by $sort




View Replies !
Query Across Multiple Tables?
I am new to mysql and need help on how to join tables. I have a database
which contains 4 tables, the main table contains information by date order
and the other 3 contain data also in date order. So I need to write a
query that retrieves all the information for one record, lets say I want to
query on the main table any entry that is for the 2004-01-06 and this date
is also in a field called 'Date' in the other tables, how do I go about
pulling back all the info for that entry across all the tables?

I have tried doing this:

WHERE main.Date = table2.Date AND table3.Date AND table4.date

however it returns loads of data when it should only pull back the one
entry.

View Replies !
Query On Multiple Tables
Tables:

patient
-------
patientID | name

scans
------
scanID | scantype | scandate | patientID


What I want to do is create a table that has a list of patient names and their latest scandate and scantype

I can't quite figure out the syntax

View Replies !
One Query For Multiple Tables
I am using MySQL 4.0

I have 4 tables w/ the same columns. Table1, Table2, Table3, Table4, under database=survey. I want to count how many surveys have been completed under each Table. Using one query, I want the total of each Count(survey_id) from each table. Basically, Select Count(Survey_id) from Table1 + Select Count(Survey_id) from Table2 + Select Count(Survey_id) from Table3 + Select Count(Survey_id) from Table4. HOw can i do this in one query?

View Replies !
Query From Multiple Tables
I want to construct one single query that gets values from three different tables

Table "A" has a column "id"
Table "B" has columns "topicid", "topic" and "userid"
Table "C" has coluns "userid" and "address"

A.id links to B.topic_id.
B.userid links to C.userid

I want to get A.id, B.subject, C.address from all three tables in one query.

Due to some other constraint, I must use left join with the first two tables:

select A.id, B.topic from A left join B on (A.id = B.topicid);

How can modify the above query to get C.address in the same query?

View Replies !
SQL Query Across Multiple Tables
I wish to make a 'Latest Comments' section, but I am unsure of the most efficient query to use.

I have comments spread across 6 different tables, named as below;

cms_artistcomments
cms_featurecomments
cms_freshtalentcomments
cms_newscomments
cms_reviewcomments
cms_wallpapercomments

Each set up as follows;

comment_id
artist_id (changes for each table)
comment_author
comment_post
comment_date

What I would like is to extract 'so many' number of comments and in reverse date order, to give the latest 'so many' comments.

View Replies !
Get Rows From Multiple Tables In One Query
Is there a way to select rows from multiple tables in one query?

Say I have the following tables and columns:Storestore_idItemitem_iditem_store_id

I want to get a store by it's id + all the items associated with that store id. Do I have to make two separate queries for this? One to get the store, and another to get all the items for that store.

View Replies !
How To Query Multiple Tables Properly
I tried to use the below code, but its only check the first row in the table only. Its not checking all the rows in a table.

PHP Code:

 SELECT books.bid,books.desc,books.img FROM books,visitor,stats WHERE visitor.ip !='$vip' AND stats.hits < '1000' AND books.bid = visitor.bid AND books.bid = stats.bid 

View Replies !
Sql Statement Query For Multiple Tables
Ive been trying to put together a php page for the last couple weeks that does a query on multiple tables at 1 time, and returns the results from each. In other words, i put in a search, it searches all the tables, then returns the results from whatever tables it finds my data in. each table is extremely different from the other, and as is the data. Im pretty sure that its just my statement that is wrong. Here is my statement but I cant seem to get it working right.

select 'table1' results from table1 where field1= '$var' or field2 = '$var'
union
select 'table2' results from table2 where field1 = '$var'
union
select 'table3' results from table3 where field1 = '$var'

$var is my search that is put in.

View Replies !
Fulltext Query On Multiple Tables?
I've built a database for an organisation, in it are 3 tables i need to include in a search, news, events, and locations. Each have a title and a description. What I've been trying to achieve (and failed at, hence me running out of time) is to have the user enter one search query, and the results page, paginated, returning matching results from all 3 tables, which will then be listed in the search as "News: ..." etc, and the plan was to order them by the fulltext score. I considered running three consecutive fulltext queries and combining them in PHP, but then I won't be able to limit the result sets for paginating them.

View Replies !
Joining Multiple Tables In One Query
I was wondering if anyone could see the best way to lay this functionality out. I have the following tables and fields (comma seperated part).

Assume the vendors userid = 5. I want to grab a list of all users that are within that vendors territory.

[table] users
userid, zipcode
* multiple users per single zip code

[table] vendors
userid, vendorid

[table] assoc_zipter
zipcode, territory
* multiple zip code per single territory

[table] assoc_venter
vendorid, territory
* multiple territories per single vendorid

Here is the SQL written out.

SELECT * FROM users WHERE
* vendors.vendorid=5
* vendors.vendorid = assoc_venter.vendorid
* assoc_venter.territory = assoc_zipter.territory
* assoc_zipter.zipcode = users.zipcode

I am trying to get this all in one sql statement. Here is a sql statement that does not work:

SELECT * FROM users
JOIN vendors ON (vendors.userid=5)
JOIN assoc_venter ON (vendors.vendorid=assoc_venter.vendor)
JOIN assoc_zipter ON (assoc_venter.territory=assoc_zipter.territory AND users.zipcode=assoc_zipter.zipcode)
GROUP BY users.userid

View Replies !
Query On Multiple Tables Events And Images
I have two tables, events and images. I want to get the data from column image_path based upon two variables, $event_date and $event_id.

The date is only in the events table but event_id is a foriegn key in the images table.

I'm really struggling with the syntax and have got really good at generating errors!

View Replies !
Delete Records From Multiple Tables In A Single Query
Here is my question, i want to delete records from more than one table.

mysql> DROP TABLE IF EXISTS table1; ....

View Replies !
Seemingly Simple FULLTEXT Query Over Multiple Tables
Can't seem to get my head around this query. Here's what I have:

I have 2 tables:

TABLE a, TABLE b:

Table a
Columns: UID, FName, LName, Bio

Table b
Columns: UID, Specialty

I want to search these FULLTEXT Indexed table columns (bio, Specialty) from the different tables for a string, and output the resulting UID and Username, one row only per UID (UID matches between tables)...

To put it another way, if the search string is found in either of the 2 columns in the 2 tables, I would like to output the UID and FName from TABLE A.

SELECT DISTINCT E.UID, E.FName, E.LName
FROM contact AS E, brg_uid_specialties AS C
WHERE E.UID=C.UID
AND MATCH (E.Bio) AGAINST ('bubble noodle Oranges')
OR MATCH (Specialties) AGAINST ('bubble noodle Oranges')"
The resulting output from my sample tables is an enormous dataset (when it should only get 1 hit), and I can't figure out why... .

View Replies !
1 Line Query To Delete Specific Records From Multiple Tables
On clients machine, currently to delete on trainee record it runs 10 queries to delete records from 10 tables. At the time of running all queries, server shows (104) Connection reset by peer. An error condition occurred while reading data from the network.

I think it because of running 10 queries at a same time. Is there any possibility that through one line of query we can delete record from 10 tables.

I've tried following query

DELETE FROM table1, table2, table3, table4, table5, table6, table7, table8, table9, table10 WHERE empID = 11;

But it gives ' error in query.

View Replies !
Combining Multiple Records Into One Based On A Key Field
I'm really scratching my head over this one. I'm working with CSV data exported from Excel, which explains why it's a mess to begin with.

Within a table (or via any other means someone might be able to recommend) I need to combine multiple records which share two like fields. (If that's not clear, the real-world explanation is below.....

View Replies !
Selecting Multiple Rows In The Based Column With AND Condition
I am facing a very big headache for a few days. I have looked through the forum for solution but found no satisfactory answer. Essentially my problem is the same as the one found in another thread, hence I use some parts of that thread to illustrate my point. Assuming the following scenario: ...

View Replies !
Multiple Table Search Based On User Input
I'm working on a database containing our research data. I know very little about PHP, MYSQL, or database structure (except keep like data together in different tables and have a key field in each).

I'm currently working with 3 tables (tbl_2006 and tbl_2007 structures are identical): ....

View Replies !
Difference Between Two Tables
i have a table A with an attribute nr(1,2,3,4,5,6,7,8,9,10)
I have a table B with attribute nr(1,5,34,56)

as a result i would like to merge these two tables i.e i would like to have all the attributes from table A ..but from table B i would like to have only 34 and 56..im not sure how this works with outer,inner,left,right joins.

View Replies !
Difference B/W 2 Tables
I am looking to figure out a way to compare two tables and show me what is different.
One table is 'usertable'.This table contains 5 columns reference(key),tag,datatype,scantime,description. When I run my application,it takes a snapshoot of 'usertable' and create a temp table 'temptags'.Every couple of minutes I want to compare the two tables and determine what is different. Fist off,I want to compare the reference column of each table and determine if there is a new reference index or if any have been deleted.Then I want to look at all the other column and determin if any have changed.
These two tables are located in different databases 'usertable' is located in 'user' database and 'temptags' is located in 'tags' database.

View Replies !
Getting The Difference Between Two Tables...
How can I use mysql query to get the difference between two pages???

SELECT * FROM
(SELECT stud_id FROM register_in)
EXCEPT
(SELECT stud_id FROM stud_***)

I used this one but I have the following massege:

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 stud_id FROM register_in) EXCEPT (SELECT

View Replies !
Query Based On Results Of A Previous Query
So far I have managed to construct one query which gives me all individuals that have one of three titles.

based on this I now want to find all the individuals that are affiliated to those listed in the first query ....

View Replies !
Joining Two Tables Or Difference Between
I have 2 tables called 'usersTBL' and 'propertiesTBL'
user info stored in 'usersTBL' and their properties stored in 'propertiesTBL'

I want to select the users from 'userTBL' which does not have any property in 'propertiesTBL' table, Both table has a same column called 'username'

the Query I wrote was

SELECT *
FROM usersTBL, propertiesTBL
WHERE usersTBL.username NOT
IN (
DISTINCT propertiesTBL.username
)

View Replies !
Time Difference Between Records From Two Tables
I have two tables with data from two separate data loggers. The timestamps of the records are not perfectly synchronised (eg. 2005-07-11 22:50:00 and 2005-07-11 22:49:58). All data must be joined to one table and all records that are out of sync by more then 30 seconds must be rejected. I tried somethig like this: Code:

View Replies !
SELECT Based On 2 Tables
I'm writing some custom stuff to pull from a WordPress install I have one one of my servers.

For one function I want to SELECT all the rows from one table based on criteria from that table and another table (they are related by the row ID of the first table). Here is the SQL I have now....

sql Code:
Original
- sql Code

SELECT DISTINCT t2.* FROM wp_term_relationships AS t1, wp_posts AS t2 WHERE t1.term_taxonomy_id = '4' AND t2.post_status = 'publish' AND t2.post_type = 'post' ORDER BY t2.post_date DESC

SELECT DISTINCT t2.* FROM wp_term_relationships AS t1, wp_posts AS t2 WHERE t1.term_taxonomy_id = '4' AND t2.post_status = 'publish' AND t2.post_type = 'post' ORDER BY t2.post_date DESC

It seems to be returning too many results. It's just returning all the rows from wp_posts that match the post_type and post_status criteria and ignoring the term_taxonomy_id (from wp_term_relationships) requirement.

View Replies !
How Can I Find Difference In 2 Tables In Different Databases With Same Structure
I am developing an application in VB.net 2005 that synchronizes two mysql databases of same structure. I have done most of the work but having problem in finding the difference in records in 2 tables. Let me explain the scenario

There is a table in the local database having name "user". The same table exists in the online version of the database. I want to find the difference of records in the 2 tables so that i can delete surplus users from the online version of the database. I am trying something like this, which is not working ....

View Replies !
Joining Tables Based On Condition
I want to have a field determine what table the field should be joint on. For example, I have a field that is one of eight different values (contacts, leads, accounts, ect...). I want to be able to join on the specific table specified by the field because this field determines what type the id field corresponds to.

View Replies !
Windows Based GUI To Manage Tables
What is best GUI to utilize to connect to my db to make edits to tables, etc...?

I thought MYSQL Administrator could do it but I can't connect to my database on a shared server... if this is to the right tool.

View Replies !
Join Query Result Difference Between 3.23.49 And 4.0.13
I have what seems to me a very common operation i'm performing. I need to find the balance on an invoice. i was not having any problems until the production server was upgraded to mysql v4.0.13-standard for pc-linux. There must be a better way to query for this information than the method i'm using, since the result with v4.0 is not what I expected, nor what I received with v3.23. I'm including sample data and queries with
my results.....

View Replies !
Date Difference In MySQL Query (3.23.50)
I am trying to calculate the age of my customers. The birthdates are stored: 19621222

I am trying:

Select (Current_Date - BirthDate)/365 as Age from Customers

Of course that is not the solution. Is there a function i can use?

View Replies !
Select And Return Based On The Relation Of Two Other Tables
I'm learning mysql and am looking for an example of how to do a certain type of search.

I have three tables and I'd like to pull records from one and order them based on the relation of two tables. My tables are: ....

View Replies !
Union Based Upon First Query
I have a query that I would like to use a union statement in to grab the number of replies to a specific thread. The initial topic thread is in a different table, which I am grabbing in the initial query... I would prefer to do this in the single query, however I supposed I could do a separate loops and grab the number of replies with a totally distinct query ....

View Replies !
Join Or Combine Two Tables Based On Unique Column
I use MySQL query browser and have made two tables in one database:

First table: Test
Column names: Filename (Varchar(255)),RowNumber(Integer),Bestandsnaam (Varchar(255)), Pad (Varchar(255)), Grootte (Varchar(255)), Created (Varchar(255)), Modified (Varchar(255)), Accessed (Varchar(255)), Deleted (Varchar(255))

Second table: Hashtest
Column names: Filename (Varchar(255)), RowNumber (Integer), MD5 (Varchar(255)), SHA1 (Varchar(255)), Pad (Varchar(255))

Of both tables the column RowNumber is the primary key. Also, in both tables the column Pad is the same (the same content, not exactly in the same order)

Now, I want to combine the two tables into one table, based on 'Pad'

I suppose I have to use the Script function of MySQL query browser. Please explain to me what I have to do to combine the two tables into one table. This third table has this columns:

Filename (Varchar(255)),RowNumber(Integer),Bestandsnaam (Varchar(255)), Pad (Varchar(255)), Grootte (Varchar(255)), Created (Varchar(255)), Modified (Varchar(255)), Accessed (Varchar(255)), Deleted (Varchar(255)), MD5 (Varchar(255)), SHA1 (Varchar(255))

View Replies !
Work Out Daily Interest Rate Based On 2 Tables
Hi

I have the following DB structure

charges
cID [bigint]
cpID [bigint]
amount [decimal 3,2]
date_charge [datetime]

petitions
pID[bigint]
interestrate [decimal 3,2]
date_claim [datetime]
And need to do the following calculation:

($amount * ($date_claim - $date_charge) * ($interestrate / 36500))
The ($date_claim - $date_charge) section needs to work out the difference in days

Is something like that possible?

View Replies !
Creating A Query Based On Dates
I am trying to write a query (in PHP) which selects from a database all of the items which are in the future. My query is as follows

SELECT * FROM news WHERE ((news.date)>$today ORDER BY date

where news is my database, news.date is the the field which holds the date for the item and $today will be replaced my current date. At the moment it seems to display all values, which suggest its not functioning properly.

View Replies !
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.

View Replies !
Sub Query - Aggregate Fields Based On Min N Max
In the Users table below there are duplicate users by email address
+---------------------+------------------------------+-----------------+-----------+
| ts | email | field1 | field2 |
+---------------------+------------------------------+-----------------+-----------+
| 2009-01-31 06:51:14 | user1@rediffmail.com | 05 | 03
| 2009-01-31 16:07:39 | user2@yahoo.com | 02 | 02
| 2009-01-31 16:15:02 | user2@yahoo.com | 09 | 04
| 2009-01-31 16:16:00 | user2@yahoo.com | 06 | 08
| 2009-01-31 16:19:52 | user2@yahoo.com | 01 | 09
| 2009-01-31 02:04:36 | user3@rediffmail.com | null | 01
| 2009-01-31 02:12:34 | user3@rediffmail.com | 01 | 03
| 2009-01-31 02:20:31 | user3@rediffmail.com | 08 | null
+---------------------+-----------------------------+--------------+-----------+

I want to fetch one record per user ‘user1,field1,field2’
For user 1
select field1 where min(ts)
select field2 where max(ts)

the final output should be
user1,05,03
user2, 02, 09
user3, 01,03 (max of ‘field2’ is null so it should pick the field value which matches the next min ‘ts’ val)

View Replies !
Totals Query Based On Days
If I have a table with a ProductID, Quantity, & DateTime field, & would like to have the sum of the Quantity calculated per product per day with blank days being accounted for even if zeroed out, how would I go about accomplishing this in one query?

Example result for ProductX:

View Replies !
Conditional Select Based On Query Results
I want to print a different message on the database, if a query returns an empty set and a different if the query returns any records. How can i accomplish that? I looked at the case statement but i can't get it working with that.

View Replies !
Query Which Gets Rows Based On A Radius, Lon And Lat Doesn't Work?
I have found this query which gets rows based on a radius. I need this for zip codes based on lon and lat's.

$sql2 = "SELECT * FROM table as z WHERE (SQRT( (69.1 * (".$userLat." - z.lat)) * (69.1 * (".$userLat." - z.lat)) + (53.0 *(".$userLong." - z.lon)) * (53.0 *(".$userLong." - z.lon))) <= ".$userRadius." )";
return $sql2;
$res = mysql_query($sql2, $connDB) or die(mysql_error());
$row = mysql_fetch_assoc($res);
based on a test zip code gives a result like


SELECT * FROM table as z WHERE (SQRT( (69.1 * (52.399834 - z.lat)) * (69.1 * (52.399834 - z.lat)) + (53.0 *(4.840762 - z.lon)) * (53.0 *(4.840762 - z.lon))) <= 100 )
the lat and lon of the test zip code are right. As you can see z.lat and z.lon don't get any value. And these would be every lat and lon in table.

In my db table lon and lat are decimal(10,6) type with a default value of 0.000000

View Replies !
Howto Make A Query Based On Another Result?
I need to make query from another query result.

tbl_A
fields: ID and Date

tbl_B
fields: ID and FileName

Code:
Select ID FROM tbl_A where Date>=CURDATE()
this 1st_query_result will be any ID with current date from tbl_A.
Then I need this 1st_query_result to query the filename which store at tbl_B.

something like this:

Code:
select FileName from tbl_B where ID = 1st_query_result

View Replies !
Time Based Reservation System - Only 1 Query Should Succeed
a user can select a time they want and submit the page

* The code selects all the bookings for a range of time.
* It then counts how many concurrent bookings there are for each hour.
* If there's less than the total (4) it inserts another row ( the user's requested booking ) into the booking table.

We also notify people if there has been a cancellation

This has led to a situation where a few different people are trying to book the same session at the same time, and succeeding!
We've ended up with 5 sessions booked

In the course of 2 page requests this seems to happen:
User1 - submits their booking
site selects to see if there's availability ( there is!)
User2 - submits their booking
site selects to see if there's availability ( there still is!)
site inserts User1's booking
site inserts User2's booking

View Replies !
Query For Month Data Based On Occurance Against Master List
I have a query running nicely. Now I'm trying to expand it.

It pulls the data from a table based on matching the id with another table and part of the grouping is by month and 2 other criteria. Now I'm trying to get the data pulled by month to pull only the info where the id matches the master file AND the FRANID's pulled are the same for each month. I'm trying to get a comparisson across times, but not every month has all FRANID's, depending on when they were entered and I ony want data that exists with matches over set months, starting for now with 12, perhaps also for 6 and 3 next time.

I've simplified what I'm doing above, but it is detailed below.....

View Replies !
Joins With Multiple Tables And Multiple Rows
I'm making a good ol' forum, and i have three tables, users, threads
and posts. when i query my threads table with a join, i need to access
the users table twice to get the username of the first poster and last
poster. But how? I can only figure out how to get one or the other. Is
my design bad? eg

SELECT TopicID, FirstPostID, LastPostID, Replies, Views, Topic,
username FROM DiscussionThreads, users WHERE
DiscussionThreads.FirstPostID=users.ID ORDER BY FirstPostDT DESC LIMIT
10 .

View Replies !
Select Multiple Keywords From Multiple Tables
am trying to do. I have a database called "members" that contains a table called "Reviews". This table has fields S1, S2, S3, S4, etc. that I want to search for the words ad, advertisement, and promotion. Here is the syntax I came up with that doesn't work:

SELECT * FROM `REVIEWS` WHERE S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, XTRA='ad, advertisement, promotion'

It would be perfectly fine, if easier, to search all fields in the table.

View Replies !
Extract Multiple Columns From Multiple Tables
For hours and hours I've been trying to work out how to write the sql query to extract some data from some tables, but with no luck.....

View Replies !
Connect/ Join Query Multiple Dbs Multiple Servers
Struggling to connect simultaneously to remotehost@my_ip_address
AND localhost@my_field_db FROM my_field_tablet_pc to affect
a custom sycnchronization that SQLyog will not allow.

Both remotehost and localhost are built on WAMP stacks.

View Replies !
ORDER Based On One Field But LIMIT Based On Another?
Say I have a table with students and their grades, and I want to get the students with the top 10 grades, but the result to be sorted based on their name. How would I do that?

View Replies !

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