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




Join 2 Simple Queries Into A Single Query?


I would like to perform both these tasks in a single query, is there some kind of AND ? to chain multiple test criteria into a single query?......




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Simple JOIN Query Issues
What I want to do is have multiple tables interact with each other.

payments TABLE
id | paidfrom | paidto | paidmethod
1 | 2 | 1 | 2
2 | 3 | 1 | 3

users TABLE
userid | username
1 | Jake
2 | Todd
3 | Spencer

methods TABLE
methodid | methodstring
1 | Cash
2 | Check
3 | Credit Card

Create Single Query From Queries On Two Tables (was "Help With Query...")
I read from other thread that query inside loop is not good idea. May I ask some help how can I create a single query to the following code which I use loop.

$sql = "SELECT * FROM mytable order by points desc limit 10";
$rec = mysql_query($sql) or die(mysql_error());
$datas = mysql_fetch_array($rec);

do{
$sq = "Select * from secondtable where linkid = '$datas[id]'";
$rst = mysql_query($sq) or die(mysql_error());
$rows = mysql_fetch_array($rst);
echo "$rows[somefield]";
}while($datas= mysql_fetch_array($rec));
This works perfectly but I want the second query to be out of the loop if there is a way and how.

Complex Queries Versus Multiple Simple Queries
I am constructing a database to contain information about stories posted on my site. Information included will be things like title, author(s), genre(s), story codes, synopsis, etc.

I worked out that storing this information properly, so that it can all be searched on, could take as many as ten tables.

My question is this: Is a single complex query really better (more efficient for the server) than multiple simple queries? In other words, I may need the information for as many as 25 or even 50 stories for a single page.

Is it better to get all of the information out of a single, massive, complex query, or is it acceptable to get the information essentially one story at a time, which could mean 25 or 50 simple queries...?

MySQL Query Cache: Should I Cache Small, Simple Queries Or Only Complex Ones?
Query cache works great for long, complex queries, but should I also be caching the simplest of select queries.

For example let's say I had a table with 100 records and I needed to select something using a unique key:

SELECT name FROM products WHERE id = 3
Is caching the above pointless, especially in terms of wasted cache memory, considering how basic it is?

Can 2 Queries Be Condensed Into 1 Query Using A Subquery Or Join?
I am developing an image gallery, and storing information about the hierarchical folder structure in which the images are organised using a modified preorder tree traversal method. I have 2 main tables:

2 Simple Mysql Queries
have problems with 2 simple queries and i dont know how to solve them. plz help me.

first one looks like this: 1.What’s the average length of the movies released in 2006? And which movie comes closest to that average length? (search upwards)

i wrote 2 separate queries: select avg(length) from film
where release_year = 2006;

and the second one: select title, length from film
where release_year = 2006
order by length;

i have to make this into one query. how do i do that? what should i write?

the second query looks like this:

One of the customers comes into the video store and he needs your help to find a children movie with 2 words to solve a word puzzle. In the puzzle the second word has 8 letters. He already knows that the 4th letter is “E” and the last 2 letters are “N” and “D”. Help him to find the movie

i wrote:

select title from film
where title like ('% ___E__ND')
and film_id in (select film_id from film_category
where category_id in (select category_id from category where name = 'Children'));

but the problem is that it doesnt return me a result. this query contains everything but the things are not in order. plz help me!

Simple Join
Just a quick question on how to make this join work.

basically here are my two tables:

tblride:

rideid|ridename
7|Spinball
10|Air|

tblslogan:

sloganid|rideid|slogan
1|7|Its Flippin Crazy
2|10|Prepare
3|10|Now Fly

With those two tables I want to basically display in a table on my page the ridename and then in the next cell the associated slogans separated by a comma.

How can this be done? Can anyone give me an example of an sql query or some php code which could do this for me?


Simple Join?
I need to find all the groupID's that employee ID=123 doesn't belong to
given the following table structure:

EmployeeGroup
------------------------
groupID
groupName


EmployeeGroupMap
----------------------------
groupID
employeeID

Ideas?

Simple Join
I have a simple join question. I need to optimize for speed. If I have two tables with a one-to-many relationship, say, [Invoice] and [Items]. And say they are joined by [Invoice]'s primary key of type AUTO_INCREMENT. Here's the question:

When I add a record in both [Invoice] and [Items], how does mysql "know" the value of the [Invoice] primary key so that it can properly insert that value in the appropriate field of [Items]?

Do I have to do a separate SELECT after I insert item in [Invoice] so I can "know" what join value to put in [Items]?

Simple Join
I need to find all the groupID's that employee ID=123 doesn't belong to
given the following table structure:

EmployeeGroup
------------------------
groupID
groupName


EmployeeGroupMap
----------------------------
groupID
employeeID.

Simple Join
I'm trying to join the vendor table whenever the equipment.vendor is equal to vendors.id. The query just shows the equipment table values and nothing from the vendors table. Did I execute the query correct?

SELECT equipment.itemid, equipment.description, equipment.vendor, equipment.reorderlevel, equipment.tonhand
FROM equipment
LEFT JOIN vendors ON vendors.id =equipment.vendor
WHERE buyer = 3

Simple Join Question
ON EDIT: I figured out the SQL syntax problem. But here's the rest of my question:

I'm trying to join two tables with information about birds, each of which share a field named "Name," which contains birds' scientific names. Most of the information I need comes from table gz_birds, but I also want to display common names, from gz_birds_names.NameCommonD.

If I write a query that targets table gz_birds only, then it displays every member of a particular bird family. For example, genus Falconidae might display a dozen genera...
PHP

$Children = mysql_query ("SELECT GZB.N, GZB.Name, GZB.Parent, GZB.Parent2, GZB.Rank
FROM gz_birds AS GZB
WHERE $Parent = '$URL1' Order By N, Rank");
But when I join table gz_birds_names, it displays just two children (genera)...
PHP
$Children = mysql_query ("SELECT GZB.N, GZB.Name, GZB.Parent, GZB.Parent2, GZB.Rank,
GZBN.Name, GZBN.NameCommonD
FROM gz_birds AS GZB
LEFT JOIN gz_birds_names GZBN ON GZBN.Name = GZB.Name
WHERE $Parent = '$URL1' Order By N, Rank");

Simple Left Join
Quote:

CREATE TABLE phpbb_anti_robotic_reg (
session_id char(32) DEFAULT '' NOT NULL,
reg_key char(5) NOT NULL,
timestamp int(11) unsigned NOT NULL,
PRIMARY KEY (session_id));

A Simple Outer Join
Sorry to post a naive question , But i need a query for this simple condition.
There are 2 tables employee and email . both have employee id as PK. I need to list employee names and emails . If enrty does not exist in email ..then it should get NULL .
Select employee.name, email.id from employee , email where ?

Simple Join Statement
I seem to be a complete idiot when it comes to join statements. Here is what I am trying to do...two tables -

TABLE tags
COLUMNS
-id
-tag

TABLE tag_assoc
-id
-article_id
-tag_id

I want to get a list of the tags for a specific article ID. The first table is simply a list of all the tags, while the second table lists relationships between an article and a tag. An article can have many tags.

Why Does This Simple Join Fail To Work?
I don't get any errors but the returned rows aren't the ones i expect from this query.

When i run the query below i get only two rows from news (2 and 5) while i would expect to receive all rows from news with either 0 or 1 for commentcount

I've narrowed down the problem to the join but i fail to see why the join excludes the other rows? Can anyone help me out with this one? Using MySQL 4.1.20

My Query:

SELECT
news.id,
news.title_nl,
COUNT(news_comments.id) AS commentcount
FROM
news
LEFT JOIN
news_comments
ON news_comments.news_id = news.id
GROUP BY
news_comments.news_id
news Table:

CREATE TABLE `news` (
`id` int(11) NOT NULL auto_increment,
`title_nl` varchar(255) default NULL,
`title_fr` varchar(255) default NULL,
`body_nl` text,
`body_fr` text,
`source` varchar(255) default NULL,
`user_id` int(11) default NULL,
`status` tinyint(1) default Ƈ',
`type` varchar(200) default 'uitgaan',
`created` timestamp NULL default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `news` VALUES (ƈ', 'A little on me ...', null, 'Brokerage, regal, symphony gold status housekeeping panoramic respectable status champagne gem saphire panoramic. Metropolitan le doctoral accredited marquis world lifestyle. Fine, echelon wealth de-jour ambassador lifestyle member gem wine portfolio affluent cruise. Wine gilded dynasty noble architectural opera travel cigar luxury ballroom echelon. World, genuine gilded de-jour first-class member theatre inspiring yacht. Noble distinctly suite auction philanthropic club designer echelon regal. Benefiting board imported benefiting stockmarket in cocktail portfolio diplomatatic fine townhome.

Diplomatatic townhome, tailored gold penthouse club reserved monogram pearl champagne, acumen symphony affluent le. Yacht stockmarket expensive grande, travel guests monogram diamond status in opulent doctoral gentlemen opulent imported. Opera inspiring five-star accredited champagne sheer designer club career.

Enthusiast panoramic handmade gifted pedigree lifestyle architectural investments benefactor acumen world housekeeping wine university dynasty. Investments, cuisine, cutlery private, auction marquis caviar imported elegant, rare, cutlery member diamond panoramic elegant.

Investments, butler rare housekeeping art investments in brokerage ladies enthusiast portfolio bonds. Private, architectural benefiting fashion with cigar member polo, using upper.

Dynasty enthusiast travel, symbolizing sport using, de-jour upper portfolio cuisine gifted private echelon le repertoire. Wine repertoire salon yacht, university travel board european echelon university gifted, luxury wine de-jour status. Gilded art on dynasty private, townhome.

', null, 'Den TVgids', ƈ', Ɖ', 'uitgaan', ��-06-22 11:13:05');
INSERT INTO `news` VALUES (Ɖ', null, 'Nieuws Test', null, 'Dit is een test van het nieuws, eens zien of het fatsoenlijk marcheert!', 'Inventis gazet', Ƈ', Ɖ', 'uitgaan', ��-06-13 11:15:55');
INSERT INTO `news` VALUES (Ɗ', 'Datum testen', null, 'Conventio olim huic velit, enim vulputate interdico jumentum ymo, si conventio, feugiat luctus. Dignissim jus, nimis abbas importunus quis conventio dolore. Feugait et neque vindico aliquip quod sed sudo humo exerci nonummy. Iriure caecus caecus delenit, aliquip praesent, facilisi iusto oppeto decet, vindico velit. Facilisi distineo demoveo ea ea eum abigo damnum.

Nulla vel ullamcorper nulla nisl quis bis euismod hendrerit regula lenis. Ymo duis in oppeto importunus damnum blandit nimis gemino minim aliquip quadrum. Valde ad praesent dolore causa consequat abdo haero duis bene in quis ingenium duis, huic. Augue mauris dolus vindico hendrerit, roto demoveo ulciscor, delenit.

Nonummy autem praemitto, enim erat abico. Vero plaga eu illum acsi ut transverbero wisi secundum hos. Premo aliquip multo os vel, lucidus feugait, illum lenis laoreet ludus. Typicus bene opes suscipit odio fatua hos dolore hendrerit decet. Praesent magna ullamcorper eu ne secundum nisl nimis incassum reprobo obruo mauris nisl blandit feugiat. Loquor tincidunt erat, utinam nimis ideo epulae, vulputate, et ideo elit eum. Acsi, in demoveo esca zelus mos roto ut quis demoveo tation letatio interdico veniam. Erat consectetuer tation duis nulla ullamcorper.

', null, null, Ƈ', Ɖ', 'muziek', ��-06-14 11:22:24');
INSERT INTO `news` VALUES (Ƌ', 'Nog een test van de timestamp', null, 'Timestamps in mysql ... argh!Ideo pecus, pagus sudo autem enim.

Enim odio, turpis et velit imputo nobis. Neque ludus multo nulla valde importunus ea.
Appellatio illum abico, duis, augue tego interdico exerci quia veniam rusticus nulla multo. Nulla jus, capto mara immitto aptent vel wisi abluo ut accumsan iaceo.

Facilisi iusto euismod lobortis, torqueo hos suscipit singularis hendrerit in. Occuro usitas fere minim usitas jumentum facilisi iriure facilisis ea te ut ad cui.

', null, null, Ƈ', Ɖ', 'uitgaan', ��-06-26 11:06:07');
INSERT INTO `news` VALUES (&#396;', 'Test nieuwtje', null, 'Dit is een test van een nieuwsbericht met een <a href="http://www.google.com">Link naar google</a> en wat <strong>tekst in het vet gedrukt</strong>.

Een nieuwe paragraag behoort ook tot de mogelijkheden', null, null, &#392;', &#393;', 'muziek', &#55614;&#57159;-06-14 10:17:15');
news_comments Table:

CREATE TABLE `news_comments` (
`id` int(11) NOT NULL auto_increment,
`news_id` int(11) NOT NULL default &#390;',
`user_id` int(11) NOT NULL default &#390;',
`created` timestamp NULL default CURRENT_TIMESTAMP,
`body` text NOT NULL,
`status` tinyint(1) NOT NULL default &#391;',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `news_comments` VALUES (&#391;', &#395;', &#392;', &#55614;&#57159;-06-26 16:12:02', 'Dit is een test reactie', &#393;');

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....

Simple Sql Question: Using A Query Result As A Query Variable
EDIT: it works now, I had an error in my code, not my method.

I have a very simple question.

I have 2 tables: 'users' and 'posts' with the following structure:

users: id, username, email_address
posts: id, user_id, post_title, post_text

in a my own mind's mysql, I would like to:

SELECT posts.id, posts.user_id, posts.post_title, posts.post_text users.username FROM users, posts WHERE posts.user_id = users.id

I usually do one query for the post data, and then, based on the use_id record, do another of the users table, but today, I'm being forced to do them in one swoop.

JOIN Vs 2 Queries
Which would be the most efficient way of dealing with this problem:

For a single productid, you want the name of the product from 1 table, and you want a list of user_comments regarding the product, from another table.

The 2 items of information are disparate, but the 2 queries can be combined very easily. Does it make sense to do so?

I'm thinking that in pure sql then no, the result set doesn't really make a lot of sense, but in a dynamic programming environment maybe it saves time spent interfacing with the database etc, and you can just pull data from the result set in whatever form necessary.

In this situation the user_comments table is pretty small, maybe the join makes less sense if the table were bigger?

Given the small size of the table I'm sure it won't make a noticable difference, but maybe I should rethink some larger problems.

JOIN Queries
Ok, so I have two tables.
One is called payment, the other one is called customer.

The payment table has 10 rows.
The customer table also has 10 rows.

In the customer table there is a field (among other fields) named fname (first name), the payment table has two fields (among other fields) call payment_received and payment_due. So what I want is a sql query where it will return the payment_due and the payment_received for a certain individual (this is where fname from customer table gets call).

I have try the following query:
SELECT p.payment_received, p.payment_due
FROM payment p, customer c
WHERE c.fname='name';

But I don't get the results that I want (it shows all 10 rows, I just one the one for that customer name).
How would I use a JOIN statement to return that result, someone told to research on JOIN stataments. Can someone help me? I have made the appropiate foreign keys, i hope.

Join Two Queries
I have no idea how to write a query for the following problem:

I have two table x and y
table x has id and name, while table y has id and value.

x.id is referencing y.id
I want to view all ids related to a particular name. So far I have achieved this much.

But instead of showing id numbers, I want to extract the value of the particular id and display it. i.e. instead of displaying
id: 1,2,3,4,5 etc.. I want to display
id: x,y,z,a,b,c etc..

Join 2 Queries Into 1
I would like to know how to join 2 queries so that the results of these
2 queries show up in the same query:

SELECT b.bios_serial_number FROM bios b:
SELECT s.system_name FROM system s;

Basically I want to create a report that includes both system name and
serial number. I'm new to this and none of the JOIn documentation was
clear to me.

Join Help – 2 Tables, 3 Queries?
Hi all – just hoping someone can offer me some advice on a query that I just can’t get my head around. For reference I’m using MySQL 3.23.

The tables I’m dealing with are;

CREATE TABLE `category` (
`cat_id` int(11) NOT NULL auto_increment,
`cat_issub` int(11) NOT NULL default &#390;',
`cat_name` varchar(255)
PRIMARY KEY (`cat_id`)
)

CREATE TABLE `site` (
`site_id` int(11) NOT NULL auto_increment,
`cat_id` int(11) NOT NULL default &#390;',
`city_id` int(3) NOT NULL default &#390;',
PRIMARY KEY (`site_id`)
)

What I need to do is;

•Find everything in `site` that has a particular city_id
•Find all the DISTINCT categories, `site`.`cat_id`, that all the sites belong to.
•(Here’s the bit I can’t do) If a the category id has a `cat_issub` != 0 then include it’s parent category in the results. The parent category’s cat_id (same table) is equal to `cat_issub`
•Only display the `cat_id`’s in the results where `cat_issub` = ‘0’

The SQL I came up with is a join, however, I can’t get it to bring up the last two points of the query’s requirements. I’m not even sure if this is at all possible, or think of an alternative PHP or MySQL function, so any help or suggestion will be greatly appreciated!

SELECT DISTINCT `cat1`.`cat_id`, `cat1`.`cat_issub`, `cat1`.`cat_name`, `cat1`.`cat_hassub` FROM `category`, `site` JOIN `category` AS `cat1` ON (`site`.`cat_id`) LEFT JOIN `category` AS `cat2` ON (`cat1`.`cat_issub`) WHERE `site`.`city_id` = '$city_id' AND (`site`.`cat_id` = `cat1`.`cat_id` OR `cat1`.`cat_id` = `cat2`.`cat_issub`) ORDER BY `cat_name` ASC

Query A Single Row
whats the best command to only get a single row, currently ive just been using mysql_fetch_array for querying multiple rows (in a loop) and also single rows. apparently theres other ways to query single rows.

Single Query
I have a question here:
I am trying to count/list all the distinct countries in my database but if one of my customer lives there.
I tried : SELECT COUNT(DISTINCT country) FROM countries,customer WHERE customer.country_ID = countries.country_ID; I know ther is something wrong here. How do I connect the two tables with their shared country_ID as a primary key? Is it possible to do this in a single query? Or do I have to first find the customers seperately then store the number in temporary table and then use the above statement?

Question About Join Queries Speed
When a thread is posted, it stores the users userid, forum it was posted in, username, post date in a table named "threads". It also stores the post in a post table named "posted" this is the query to view threads when the forum=1 ....

Can Mysql Join 2 Queries Into 1 Record Set?
if I cannot make a query work can i combine the results of 2 different queries into 1 record set?

can we combine records from :

SELECT RESTNAME AS SET1 FROM RESTAURANTS WHERE RESTCITY = '$city'

SELECT RESTNAME AS SET2 FROM RESTAURANTS WHERE RESTZIP = '$zip'

I know this is an easy example and we can combine them in 1 query, but for complicated purposes is there a way to combine both sets and sort the full set ....

somthing like JOIN SET1 ON SET2 ???

Simple SQL Query
I was wondering if anyone could help me with this SQL query?

I'm making a football prediction website and I want to be able to display the weekly fixtures in a GridView so the admin can edit, insert, etc.

This is a simple version of the two tables that I have: Fixtures and Clubs...

CREATE TABLE Fixtures
(
MatchID Int PRIMARY KEY,
HomeClubID Int,
AwayClubID Int
)

CREATE TABLE Clubs
(
ClubID Int PRIMARY KEY,
Name Nvarchar(50)
)

.. where HomeClubID and AwayClubID are actually foreign keys to ClubID.

My Problem is that I'd like to create a query that will show each fixture with both the names of the home and away clubs on the same row, eg:

| MatchID | Name | Name |
|--------------------------------|
| 1 | Arsenal | Man Utd |
|--------------------------------|
| 2 | Liverpool | Chelsea |

... etc.


Help With Simple Query
I know this is easy to accomplish, but my brain is fried and I can't figure it out.

I have a few markets (areaID) that vendors belong to. Within these markets, vendors are assigned categories (catID).

I am trying to do a SELECT on the vendors table to find out the total number of vendors to a particular category, within a particular market. So essentially, I want to know the number of vendors within each category within each market. Does that make sense?

Can Anyone Help Me With This Simple Query?
In my database. I want to pull out one record:

Where the date I wish to publish a story where the published_web_date(date) is less or equal to now
and
The published_web_time(time) is less or equal to now

However, using the below query data is nomatter what the published_web_date is if the published_web_time has not elapsed then nothing is shown.

select * from cms_stories
WHERE section = 'news'
AND published_web_date <= NOW()
AND published_web_time <= NOW()
ORDER BY story_id
DESC LIMIT 1";

A Simple Query?
In table "vb_user" I want to pull the data in field "username" and copy that username in another table called "vb_userfield" in a field called "field5". Both tables share the field "userid" which is how the relation is made. I know this is probably very simple but man... I just can't seem to pull it off.

I've got about 500 members and I really want to populate that field "field5" with thier username without having every one of them doing it manually.

Simple Query
I was curious as to what is the best way to determine if a SELECT query was successful in retireving any rows? I've been using..
IF(!$getline){echo "no rows found"
but if there were rows found I would have to run the same query again so I can print them. Is there another way?

$get="select * from orders'";
$getresult=mysql_query($get, $link) or die(ErrorDB($realname));
$getline=mysql_fetch_array($getresult, MYSQL_ASSOC) or die(ErrorDB($realname));

Simple SQL Query
I am looking for some help on a simple (yet beyond my reach) SQL query that I can run via phpMyAdmin whenever I need to.
In a nutshell, I have a Database called A with table B, in which fields C and D sit. For each record, field C has an integer and field D has a human-readable date/time entry in the format: 2005-08-23 17:35:33.
It is important to note that the above date part is YYYY-MM-DD as the convention might be different in your locality.
Anyway, I am looking for an SQL query that will go through the table and whenever the date/time shown in field D is no more than 5 days ago, to add X (some whole number chosen and manually specified in the query each time it's run) to the value in field C

Simple Query
At least I think it should be simple, but I can't get it.

SELECT * FROM 'tableA'
WHERE 'tableA.id' = 'tableB.target_id'

Which returns an empty set, though

SELECT * FROM tableB
WHERE target_id = "b327f34a-54ea-071a-3b9d-451810085fb9"

and

SELECT * FROM tableA
WHERE id = "b327f34a-54ea-071a-3b9d-451810085fb9"

both work. That is to say that there is a record in tableA WHERE, tableA.id = tableB.target_id for AT LEAST one record in tableB

Update A Set Of Records In One Single Query
My records contain a position, from 1 to n. This position is not the primary key.
In normal conditions, the position of this records should be as follows:
1, 2, 3, 4, 5, 6, 7, 8, 9 . etc...

One of my utitities is meant to check the consistency of the table -
one of the things it has to do is scan the table as follows:

SELECT position FROM employe_records WHERE employe_id = ? ORDER BY position

From the result of this query I verify each entry (JDBC) one by one, looking for inconsistancies. In a for() loop I look at the value of position and check that they start from 1 and are incremented by one for each record.

At the first inconsistency I come accross I want to run a query to update the records so it is consistant again - it is something like this:

UPDATE employe_records SET position = updatedValue FROM
employe_records WHERE employe_id = ? ORDER BY position

This is not valid query of course - my question is what should my query look like?! How can I make 'updatedValue' incremented by one automatically so each of the records are updated from 1 to n.

Multiple Selects In A Single Query
I wonder if there is any way to use more than one select in a statement, like this one:

How Can I Update A Set Of Records In One Single Query
My records contain a position, from 1 to n. This position is not the primary key.
In normal conditions, the position of this records should be as follows:

1, 2, 3, 4, 5, 6, 7, 8, 9 .etc...

One of my utitities is meant to check the consistency of the table - one of the things it has to do is scan the table as follows:

SELECT position FROM employe_records WHERE employe_id = ? ORDER BY position

From the result of this query I verify each entry (JDBC) one by one, looking for inconsistancies. In a for() loop I look at the value of position and check that they start from 1 and are incremented by one for each record.

At the first inconsistency I come accross I want to run a query to update the records so it is consistant again - it is something like this:

UPDATE employe_records SET position = updatedValue FROM
employe_records WHERE employe_id = ? ORDER BY position

This is not valid query of course - my question is what should my query look like?! How can I make 'updatedValue' incremented by one automatically so each of the records are updated from 1 to n.

How To Get MY SQL Query Messages Into A Single Outfile
I want to run set of queries and want to get the messages after executing them into one outfile.

e.g when I run query "Select * from accounts", when the query is successfully executed, it gives message "1000 rows in set (0.01) sec".

I want to get all such messages from different query sets into one outfile.

Can anybody guide me on how to get the same?

Need Single COUNT Value For Complex Query
I have a moderately complex query and I want to page the results, limiting to 50 on a page. I know that in order to do so, I need to know the total number of records so that I know whether there are more records remaining so I can show a 'NEXT PAGE' link.

I'm having trouble constructing a COUNT query from my original query because the query accesses 4 tables, two of which are many-to-one association tables. Here is the original query, without a LIMIT clause:

Simple Query That I Can't Figure Out
First off, here's my table:
CREATE TABLE order_info (
ID int(10) NOT NULL auto_increment,
ordernum int(10) NOT NULL default &#390;',
item_code text NOT NULL,
item_qty int(5) NOT NULL default &#390;',
item_price text NOT NULL,
have int(5) default NULL,
standby int(5) default NULL,
backorder int(5) default NULL,
refund int(5) default NULL,
`status` int(2) NOT NULL default &#391;',
PRIMARY KEY (ID),
KEY ordernum (ordernum),
KEY `status` (`status`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 PACK_KEYS=0 AUTO_INCREMENT=477150 ;
I would like to make a simple query that returns ordernum's that match this critera:
All of the items have a 'status' of 3
Have at least 1 'refund'
and I would like the ordernum's returned to be distinct.

Here's the query I had before the requirement of the 'refund' column:


SELECT
DISTINCT order_info.ordernum
FROM
order_info
WHERE
order_info.ordernum NOT IN (
SELECT
order_info.ordernum
FROM
order_info
WHERE
order_info.status != 3
)
AND
order_info.status = 3
I tried adding:


SELECT
order_info.ordernum
FROM
order_info
WHERE
order_info.ordernum NOT IN (
SELECT
order_info.ordernum
FROM
order_info
WHERE
order_info.status != 3
)
AND
order_info.status = 3
AND
SUM(order_info.refund) > 0
GROUP BY
order_info.ordernum
But it returns incorrect information (orders with 0 'refunds').

What is the correct way to make this query?





Bug In A Simple MySQL Query
Having a problem with a very simple query I am trying to execute. Hopefully someone can shed some light on the issue.

SQL Query

SELECT tblUserInfo.PersonalID, tblUserInfo.mainPicLink, tblUserInfo.Location FROM tblUserInfo, tblCoreUser
WHERE tblUserInfo.Orientation = 'Straight'
AND tblUserInfo.Location = 'Hampshire'
AND tblUserInfo.PersonalID = tblCoreUser.PersonalID
AND tblCoreUser.usrSex = 'M'
LIMIT 10;
Error:

Unknown column 'tblCoreUser.PersonalID' in 'where clause'



A Simple Query Question ...
The following returns one row -

PHP

SELECT ab.id, ab.menu_name, ab.keywords, bb.content, NULL , NULL , NULL , NULL , NULL , NULL
FROM menu_management AS ab
JOIN dynamenu_content AS bb ON ab.id = bb.menu_id
WHERE 1 =1
AND bb.publish =1
AND ab.version = 'fr'
AND ab.menu_name LIKE '%Nanotechnologies%'
OR ab.keywords LIKE '%Nanotechnologies%'
OR bb.content LIKE '%Nanotechnologies%'
LIMIT 0 , 30

But the following returns zero rows

PHP

SELECT ab.id, ab.menu_name, ab.keywords, bb.content, NULL , NULL , NULL , NULL , NULL , NULL
FROM menu_management AS ab
JOIN dynamenu_content AS bb ON ab.id = bb.menu_id
WHERE 1 =1
AND bb.publish =1
AND ab.version = 'fr'
AND (
ab.menu_name LIKE '%Nanotechnologies%'
OR ab.keywords LIKE '%Nanotechnologies%'
OR bb.content LIKE '%Nanotechnologies%'
)
LIMIT 0 , 30

In fact I am trying to make a query (which will later be with other queries thro' UNION ALL) where upto ab.version = 'fr' will remain constant, but the following part will change.

Means, among ab.menu_name, ab.keywords and bb.content, there may be all the three, or two or one condition only, depending on user's input. Also, the condition between them can be OR or AND, depending on whether user tends to search for all or any matches.

Simple Between Query Problem
I have multiple fields on my form where a user submits a minimum and maximum value. Such as minimum price and maximum price, so I use a Between in my queries like this.

SELECT COUNT(*) AS 'numrec' FROM tblmls WHERE mlsstatus IN('Active', 'New', 'Back on Market', 'Price Change') AND mlsclass = 'Residential' AND mlslistprice BETWEEN ?' AND ?'
My question is, is there a way to do wild cards using a between statement? Or is there a better way to do this?

Currently if they don't put anything in I don't run that part of the querie, but if they put in a minimum but no maximum I just autosubmit a large number. If they put in a maximum but no minimum I just submit a 0.

Simple Query Problem
I'm a newbie having trouble properly executing a simple query.

I'm trying to make a pathway to prevent tennis players from signing up more than once on a specific date.

Here is my

PHP

$play_date=($_POST['play_date']);
$user_id=$_SESSION['user_id'];

// Make the query to check if the player already signed up on that date.
$query = "SELECT user_id, play_date
FROM table
WHERE user_id=$user_id AND play_date=$play_date
";
$result = mysql_query ($query);
if (mysql_num_rows($result)>0) {

echo '<p><font color="red" size="+2">Sorry, you already signed up to play on this date!</font></p>'

} else {

Although the above code runs, it doesn't prevent one from signing up twice on the same date.

Simple Query Trouble
I have written a simple select query...but it is not doing what I want it to:

$query = "SELECT * FROM helpdeskticket WHERE (`customerid` = '$customerid') AND (`helpdeskticket`.`status` = 'Assigned') OR (`helpdeskticket`.`status` = 'Unassigned') OR (`helpdeskticket`.`status` = 'Can Be Closed') ORDER BY `helpdeskticket`.`ticketid` DESC

Because its wrong i'll explain what I wish it to do. Select all fields from helpdesk ticket where customerid is equal to $customerid, and the status is either assigned, unassigned or can be closed. Then order by ticketid descending.

At the moment it seems to be messing around with the AND and the OR, and is selecting everything from the database table, ignoring the customer id.

Simple Not Distinct Query?
I have a very large product table and believe that some of the fields contain duplicate values when they shouldn't. So I'm trying to create a simple query to identify those that do.. ie something like

Select modelnumber from tbl_product where modelnumber is not distinct

OR

Select NOT Distinct modelnumber from tbl_product.

These obviously don't work (Otherwise I wouldn't be asking for help!), and was wondering if there is a not distinct function that im missing or misusing?

Simple Count Query
I am trying to use the below query to count the number of images held for each book. Unfortunately it is only returning the books with images. I would like all books returned even if they have no corresponding image.

SELECT tblBooks.Title, tblBooks.Description, tblBooks.Author, tblBooks.Annotation, tblBooks.Collection, tblBooks.Price, tblBooks.SortID, tblBooks.Heading, Count( tblImage.ImageID ) AS CountImage
FROM tblBooks
INNER JOIN tblImage ON tblImage.BookID = tblBooks.BookID
GROUP BY tblBooks.BookID

Mysql Simple Query
I am doing a project in mysql and php..
While inserting the data, i made a mistake of inserting date values into the month field and viceversa. can i swap it with a query. I cant take a backup of this table.. because its very big and the webspace for mysql database for me is running very low.

ONE MORE THING :- there are many tables almost 565... can this all be swapped in a single query or procedure.

Simple Null Query
How do you say I want to select all data from this column but only show the data where the data is not equal to null.
I have;

SELECT prevleaving1
FROM `jobemployment`
WHERE prevleaving1 IS NOT null


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