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.





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 Complete Forum Thread with Replies

Related Forum Messages:
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 !
Select Records Without Relation.....
I've 2 tables and the relation between them is the id. I want only select the records from table A which are not present in table B!

View Replies !
Is There A Relation Between Number/size Of Total Tables & Table Operations In The Same Db
Does the number of tables and their total size in one DB influence the time needed by MySQL to perform a SELECT/UPDATE/DELETE operation on a certain table?

I'm wondering about how I should backup information, which become obsolete on a monthly basis and therefore should cease to exist in the table. Just keeping the records in the table and append the new information would certainly slow down all of my queries. Now the question is: is there any disadvantage of creating new tables for each set of data(monthly) in the same database compared to simply creating an external file backup?

View Replies !
Select Based On FK
I have two questions regarding the MySQL v4.1.16 scenario below:

1. What should the FK on update and on delete parameters be (i.e., default, cascade, restrict, no action, etc.)?

2. How can I insert the correct id’s as implied below?

I have tried just about everything (including “Insert …select”, “LAST_UPDATE_ID();”, etc.) and whenever I think I am starting to get close I either get more errors or ‘0 records added’ with no error message;

I would greatlyappreciate someone who could instruct me on how to accomplish this task.

View Replies !
Select Based On Rarity?
I have a table and one column is titled "rarity." Every once in a while, ONE random row from this table will need to be selected... I want to select the random row based on the rarity column. All of the rarities would equal 1. For example, a rarity of .38 would have .38 probability of being selected from the table.

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 !
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 !
SELECT Based On All Day Names And Their Hours
I have a table which has a DATETIME column which stores datatime for each record.

I wanted to calculate the total/average of the records for each day and then for each hour of that day ALL TIMES like not only the current week or current month or year but for all available records.

a sample output can be

Monday
00 (count value)
01 (count value)
02..... (count value)
23 (count value)

Tuesday
00 (count value)
01 (count value)
02..... (count value)
23 (count value)

...

Sunday
00 (count value)
01 (count value)
02..... (count value)
23 (count value)

I tried something like following

SELECT count(id) as cnt,HOUR(hitdate) as hr, hitdate FROM hits GROUP BY DAYOFWEEK(hitdate),HOUR(hitdate)

And I am getting the following results, (long result)

cnt hr hitdate
1274 0 2008-07-27 00:00:50
1235 1 2008-07-27 01:00:07
921 2 2008-07-27 02:02:13
830 3 2008-07-27 03:00:03
674 4 2008-07-27 04:02:49
617 5 2008-07-27 05:00:37
606 6 2008-07-27 06:01:41
545 7 2008-07-27 07:01:52
534 8 2008-07-27 08:05:58
630 9 2008-07-27 09:04:01
680 10 2008-07-27 10:04:41
688 11 2008-07-27 11:01:26
881 12 2008-07-27 12:00:22
745 13 2008-07-27 13:00:09....

View Replies !
Select Columns Based On Subselect
Is it possible to do the following:

select (select from factors where type='factor_1') from survey_results where last_name='some_name';

I get the error: "#1242 - Subquery returns more than 1 row"

Can I convert the rows to a list?

More info if needed:

I have two tables, 'factors' and 'survey_results'. A survey_result row contains a list of factors (> 30). Factors can have different types. For a survey result I'd like to select only the columns related to a certain type of factor and analyze just those factors (e.g., find the min and max scores). I don't want to hard code lists of factors of certain types to use in my outside select statement. I'd like to do it dynamically based on the factors table.

View Replies !
Select Statement Based On Bytes
I have a table with an attribute named "message" with a varbinary type in which information is being stored in. It contains a total of 10 bytes and I want to select ONLY bytes 4-7.

View Replies !
Mysql Select Based On Datetime
I am having an issue returning a known record based on a date field that is of datetime format from mysql.

the data looks like this in mysql: 2006-01-26 20:01:45
here is the eror I receive:
SQL error=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 ཐ:01:45' at line 1

this is the select statement I am using

("SELECT selections from your_show WHERE userid = $userid and date = ".rawurldecode($date)." ");
$date is passed as 2006-01-26%2020:01:45


View Replies !
Linking Tables Return One Row
If you have a number of linked tables is there some way to return just one row where fields with many values are put in an array? When I do my JOIN query I get a matrix of results showing every possible combo of the linked tables i.e.:
maintbl---tbl1---tbl2---tbl3
1-----------1------1------1
1-----------1------1------2
1-----------1------1------3
1-----------1------2------1
1-----------1------2------2
1-----------1------2------3
What I would like is:
maintbl---tbl1---tbl2---tbl3
1-----------1-----1,2---1,2,3

View Replies !
Substr Return From Select
Can I do this? Can't find any ref.

select substr(col1,1,3) from table ...
select col1[1,3] from table

The column contains ABC123, DEF456, etc

I want:
ABC
DEF

View Replies !
SELECT On Return Of Update
I need select a record choosing it on return of record count of update. I would like use a unique query. I developing in php and mysql_query not support multiple queries.
I tried many functions for example:

select * from messages where id_msg= (count(update table set record=1))

but MySQL tell me always there is a syntax error.


View Replies !
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 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 !
Select Record Based On 'change' Date
I currently have a database containing a table with the following fields:
signid, sign_typ, changedate and time.

The 'changedate' field is the date on which the star sign changes and becomes 'active' until the next 'changedate' in the table. I am trying to search this field by a date the user enters and display the 'sign_typ'.

View Replies !
Select Based On Two Rows In Mapping Table
I have a many to many relationship between a resource and tag:

resource - 1:M - tagged_resource - M:1 - tag

So a resource can have many tags and a tag can belong to many resources. The data would look like this:

RESOURCE TABLE
id: 1
name: resource1

TAG TABLE
id: 1
tag: new
id: 2
tag: tested

TAGGED_RESOURCE
resourceID: 1
tagID: 1
resourceID: 1
tagID: 2

How can I select the single row from the RESOURCE TABLE which has the tags 'new' and 'tested' in the TAGGED_RESOURCE TABLE?

I have tried using 'IN' but it acts like an OR operator rather than AND.

View Replies !
Can SELECT Return The Position Of The Results?
I have a table with values:

Row: Name Row: ID
John 4890
Mark 4922
Peter 4934
John 4980
Joe 5029
Lisa 5044
etc...

What I need is a query that I would do for example on John (name='John') that would return the following:

location
1
4

In fact the only thing I need is the location of the John in the resulting table. Apart from the Name column I do have other column of ID's. They are incremental but not step 1 if this can help in any way. Is something like that possible with one query?

View Replies !
Multiple Selects Return Only Last Select
SELECT * FROM `logs`;
SELECT * FROM `msd`;

If I make this query (from phpmyadmin, I don't have client access), I only get the results from the second query, although phpmyadmin does admit that the first query returned 7 rows.

I should have seen a total of 8 rows, because that's all the rows there are in these two tables. I don't get an error message.

I can do the two queries separately and it adds up to 8 rows. I can't do a UNION because they have a different number of columns (and I don't want to do a UNION).

Is there some setting for the MySQL server that prevents multiple queries?

This also doesn't work through php (using multi_query).

View Replies !
SELECT Count(xxx) AS Xxx Does Not Return Integer
i'm using the latest downloaded version of MySQL and am currently producing an app that is compatible with MySQL, MS Access and SQL 2000/2005, i've not really come across any problems making the app run across the 3 platforms (except for Access's wierd date syntax and MySQL's lack of a boolean field) but the followin is doing my head in:

If i run a count query such as

SELECT Count(CategoryID) AS CountCats FROM MyDownloads etc etc
CountCat = (Downloads.Fields.Item("CountCats").Value)

And then run an IF statement in my page code such as:

<% If CountCat = 0 Then .... %>

This works fine in Access and SQL as the Count value is seen as an integer, but in MySQL this chucks an error unless the code reads

<% If CountCat = "0" Then .... %>

Why is the count value not returned as an integer????? I cant understand that at all, what else could it be? I've seen another post on the forum along the same lines but with no answer to it.

This is grim as every page that uses a count needs to have an additional IF statement put on it to change the second IF statement if the database is detected as MySQL.

View Replies !
USE SELECT SUM(.....) ;WILL RETURN BLOB TYPE
i use mysql5.0.4 and Connector/NET to write asp.net project;WHEN I use "SELECT SUM(.....) as a",I found it will return blob field type;but in mysql4.1.11 will return double type ; can help me to convert blob to double

View Replies !
Select Group_concat Doesn't Return Numbers?!?
Say that I have a table with a with of integers and a row with text. For starters, I just want to have the integers returned in one string:

select group_concat(MyIntegers) from MyTable;
This gives me a lot of questionmarks: ?????????

However, if I do this, I get the real result:
select lower(group_concat(MyIntegers)) from MyTable;
This gives me: 11,15,20,etc.

If I select the string row, no extra work is needed.
select group_concat(MyStrings) from MyTable;
I get: "blabla,hey,there" etc.

Why can't I get the numbers "as is" in the first query? I'm using the latest 5.0.19 Win32 MySQL server, running the latest ODBC driver etc. on a Windows server 2003.

View Replies !
Many To Many Select Using DISTINCT Or Not Return The Same Results
I was on MySQL website looking for an answer, but still need assistance please.

I want to do the opposite of the following:

SELECT * FROM myTable WHERE id IN(1,2,3,4,5) ;

I want to use my array(1,2,3,4,5) to exclude items in the result set, not include them.

So, I want to do something like this:

SELECT * FROM myTable WHERE id NOT_IN(1,2,3,4,5) ;


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 !
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 !
CREATE Tablename Based On Result Of SELECT Statement?
Is it possible to have an CREATE statement that contains a SELECT in the section of the CREATE that specifies the TABLE?

I want to have a sql script that can execute SELECT YEAR(CURDATE()) and SELECT MONTH(CURDATE()) to give me the Year and Month and then use these to create the Table Name: tbl_MetaData_2008-03

Example:

CREATE TABLE tbl_MetaData_X-Y
( ...

Where X is the YEAR and Y is the MONTH

View Replies !
SELECT DISTINCT Sum(): Return Multiple Rows
i am having big headaches in trying to find out how to perform a very very simple query.

having a table like this one: ...

View Replies !
Column Name Is SQL Keyword(Return) In SELECT Query
Is there a setting in MYSQL server that let it accept Select queries with Column names that also are keywords? "Return" is a keyword now in MySQL.

Motivation:

We had an old delphi application that uses a mysql database.
Somehere in code it does:

SELECT Return from CarUse;

(Actually it does more but the above is the isolated problem.).

Return is a Column name in the CarUse database.

In our old setup with an old mysql database, the above code was accepted. I migrated the database to a new server with a new MySQL. The above code is no longer accepted.

View Replies !
Select To Return A List Columm Without GROUP_CONCAT
I allready try something like this...

select name,(select ID from table where id = X.id)
from table X
group by name

-> return a columm with all "grouped" IDs
john, "12,12,1,2323,54"
marta, "1222,11,2"
josh, "69,87"

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 !
Optional Relation
i have one table which has 4 optional relations many-to-one with 4 other tables. With DB designer I have defined 4 optional relations, but when i do the forward engineering the script contains 4 foreign keys, which are a too strong tie from implementation's point of view.

View Replies !
Setting Up A Relation
Is there any reason why two tables created with a relation in MySQL
wouldn't adhere to what you would think is a property of the relation?

Case in point: I have a 1:n 'relation' where I can insert values into
the dependent table while making up an entry for the foreign key from
the independent table (whether it exists or not). I shouldn't be able
to do that, but MySQL doesn't complain.

View Replies !
Db Design - The Mythical 1:1 Relation
I'd like to split an entities's attributes because they won't get
equally frequently requested. So I can save memory and disk access time.
The integrity of the splitted record should be retained.

The key points would be:
1) devide the data collumns on n tables
2) enforce the existence of all parts of a record by table design


The best workable way I can think with only two tables is 1:(0,1)
which is not exactly the deal. It provides that table_b can hold 0 or 1
part relating to a part in table_a, by a foreign key in table_b and an
UNIQUE.


I tried another way with
1) creating table_a
2) creating table_b with FK to table_a
3) alter table_a with a FK to table_b

Now that was a 1:1 relation.
Obviously I couldn't insert anymore. A insert in table_a would violate
the existence integrity constraint to table_b.

SET AUTOCOMMIT=0;
SET FOREIGN_KEY_CHECKS = 0;
insert table_a ...
insert table_b ...
SET FOREIGN_KEY_CHECKS = 1;
COMMIT;

would let me insert but the inserted data wouldn't be checked at all.
That way I could forget using this relation constraint alltogether.

View Replies !
Delete Cascade In Many To Many Relation
I have table A and B that has many to many relation (Table C is the many to many) I want that when i delete records from A, the records from C and B will also delete.I set on delete cascade in C table FK (for A and B) but when i delete records from A it delete only A,C. Is there any way to delete A,B,C when i delete records from A??? I know that the problem is that this is many to many , so there is an option that some records from B will be delete despite the fact that they have also relation with records that has not deleted, but i dont care to delete those records.

View Replies !
Entity Relation Ship
I am trying to find entities and their attributes, the entities are listed in the problem description and I have to find them, but dont know where to start and how to find them. DO they come in noun forms like classes in programming.

View Replies !
Relation Diagram Tool
Are there any free entity relationship diagraming tools for MySql 5.0 ?

View Replies !
Foreign Key Constraints - Many To Many Relation
I have 3 tables and there is an issue that I can't resolve, so looking for advice

The table(s) are Products, Catalogue and Catagories. A Product has one or more Catagory(ies), taken from the Catagories table, and mapped with the Catalogue table, ie
- Products
SCH1000 ... ...
- Catagories
193 Books ... ...
- Catalogue
SCH1000 193
There are two constraints on the Catalogue table; One for Products and One for Catagories, so if you delete a Product, the relation is deleted from Catalogue, and likewise if you delete a Catagory, the relation is delete from Catalogue.

However, for example, if you delete a Catagory, then the Product(s) assigned to that Catagory is not deleted and still remains, so you have a broken relation. So my question is this... What changes do I need to make, so that if a Catagory is deleted, the related rows are removed also? I need the row(s) deleted both from the Catalogue table, and the Products table.

But MySql (rightly so) will not allow me to put foreign key constraints on either the Catagories, nor the Products tables. The many to many relationship is a requirement and is not something I can get around.


View Replies !
Configuration And Usage Of The Relation Feature
im just creating a new database for a browser roleplaying game. Maybe you can imagine how complex this can be sometimes. And while i was working on it i remembered a feature of the MS access database. At access you could create relations for various tables, so if u change a field in one table, it is changed for all fields related/linked to it.

Is there a similar feature in mysql, and if yes, is it the "linked_tables" feature?

View Replies !
Size Of DB In Relation To System Specs
i'm running a server with two dual core processors at 3 Ghz and 8 GB RAM. The size of the MySQL-DB on this server is 1.5 GB. Most of these 1.5 GB (70%) are not processed during normal usage.

At the moment everything is running fine, but i'm expecting the DB to grow during the next month, so I ask myself at which size the system speed will start to noticeable slow down.

View Replies !
Relation With Comma Separated List
i want to know how it is possible to relate two tables over a field with a comma separated List, which are the forein keys of the other table (table TWO).

Table ONE is for article and has the three fields uid, titleArt and categories
Table TWO is for categories and has the two fields uid and titleCat.

The field categories of table ONE is the ID-List with UIDs from table TWO separated by commas. Now i want to get the title of the categories (titleCat) related to the articles in a new virtual field like category also separated by comma.

I've tried it in the following way:
SELECT article.titleArt, categories.titleCat GROUP_CONCAT(categories.titleCat SEPARATOR ', ') AS category from article,categories where uid=2 AND categories.uid IN (article.categories) GROUP BY article.titleArt

But unfortunately i get only one (from the first id in the list) category-title (titleCat) in the new virtual field category.

View Replies !
What Is The Relation Between Innodb Log File And Buffer Pool ?
With regard to innodb_log_file_size, MySQL doc says:

====================

Sensible values range from 1MB to 1/N-th of the size of the buffer pool, where N is the number of log files in the group. The larger the value, the less checkpoint flush activity is needed in the buffer pool, saving disk I/O. But larger log files also mean that recovery is slower in case of a crash.

====================

Why should the total size of log files in the group be equal to the size of buffer pool ?

View Replies !
Query That Finds Last Row In Relation To Current Row (read For More)
It's been almost a year since I last did SQL and I can't for the life of me figure out how to do this again.

Pretty much I have a table like so:

id | ip | time

I want to get a result set that contains each unique ip, how many times it appears in the table, and the last time it appears.

View Replies !
Select Data From 1 Table Based On Criteria From Another Table
is it possible to select all the data in one table based on a criteria from another table?

for instance i want to select all the therapist from massage_therapist WHERE massage_schedule.finish > 0.
i don't want merged results. i just need to list all therapist based on the where criteria from a different table.

these two tables have the therapist_id in common.

View Replies !

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