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




How To Specific Number Of Records To Retreive In A Query?


My item file contains too many records to display. I want to limit the display to only 20 records at a time.

In the Select statement, how do I specify the the first 20 records, 2nd 20, etc.?




View Complete Forum Thread with Replies

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

Retreive All Records
I've searched the forums and found posts close to what I'm after, but not exactly (and I apologize if this has been covered). Here's my question:
All my data is inserted into my db once a day at the same time (and it has the same datetime value for the "RatesUpdated" column). I want to retrieve all data that was inserted on the most recent day only. Here's my failed query:

SELECT t1.Product, max( t2.RatesUpdated ) AS LatestDate
FROM `mortgage_rates` t1, `mortgage_rates` t2
WHERE t1.RatesUpdated = LatestDate

I'm on mysql 4.0.22. What must I do?

List The Number Of Records In Query
I have a very simple query. I want to list a bunch of names & how old they are. (two columns) I want to add a third column that basically counts how many records there are.

Example:

1. Bill Jones - 55
2. Bob Smith - 56
3. Steve Gates - 25

Can I do this in mysql or should I add the code in PHP, and how do I do it?

Query To Display Records Over A Certain Number?
think my brain is now officially fried as i can not come up with this query....

i want to display records from my table where the record count is say over 5.

real simple...two columns a and b.  10 records in the table....

Using Limit On Grouped Query With Large Number Or Records
I have a query that use a "group by" clause that returns 600+ queries

however if I add a LIMIT 500,50

It returns 0 records. I tested LIMIT 450,50 and it returned only 34 records.

Is there something limiting the limit? Is there an option in mysql that can increase this limit?

Finding Around An Specific Number?
I have a page in php and mySql and in my query I look for a number that's been input from a dropdown in a form.

Let's say I pick number 5.

So I put WHERE number LIKE $number to get what I picked.
But now I wanna get the number picked and also the 3 lower numbers as well.
So if I pick 5 I would get 2, 3, 4 and 5.
If I pick 20 I would get 17, 18, 19 and 20.

Is there a simple way to do this in the query?
Is there something I could use for this, just as I can use = or < and >.

Week Number In Specific Month
I have a problem regarding the week number in specific month.....

i would like to get the week number in that certain month by just providing the date......

for example :
2007-10-07 - week 1 (oct)
2007-10-14 - week 2 (oct)

but i want it to return me 1 when i provide (2007-10-07 to 2007-10-13) and return me 2 when i provide (2007-10-14o 2007-10-20) ..... and so on.... it is possible ?

How To Get Records Between Two Specific Dates?
i'm a newbee to mysql.

i'm having a table called transaction which stores transaction details with dates.

i'm having another table callled company in which the company info stored,

The company table has the fiscal month details.

what i wnt to do is get the records from the transaction which is between two specific dates(i.e) in the fiscal year

eg: 04-01-2006 to 03-31-2007

as far as now i'm having the query,

SELECT t.* FROM transaction t,company c where t.companyid=c.id AND
(MONTH(t.transdate)>MONTH(str_to_date(c.fiscalmonth,'%M')) AND
YEAR(t.transdate)=YEAR(now())) ||
(MONTH(t.transdate)<MONTH(str_to_date(c.fiscalmonth,'%M')) AND
YEAR(t.transdate)=YEAR(now())+1) and c.id=2 order by transdate
Note: the company table stores the fical months as month names(i.e) March etc.,

i think this is far complex, and is there any easy function to get the records b/w two dates??

Selecting Specific Records
I have two tables. I want to select the last record for a specific type from one table and look up info from the other table. Is there a command that will select go to the last record of a query?

Retrieving Specific Records
I am trying to establish (using a straight MySQL query in version 4.0.18)
the level of qualifications someone has, i.e. degree, postgraduate degree or
other.

To simplify things, I need to use only two tables, namely:

master table, containing:
staffno (Primary Key);
forename;
surname;

psnquals table, containing:
psnqualid (Primary Key);
staffno (Foreign Key);
levelid (where 1 = degree, 2 = postgraduate degree, 3 = other)

In the followning query, staffno 1 has three qualification levels, 1, 2, 3.
The query finds the first matching record (where cdelevelid = 1) and then
stops, making it appear as if the employee had no postgraduate
qualification.

One person can have one or all of the above qualifications. I need to write
a query that shows if a person has one, two or all of the above. I tried
using the following query, but it seems only to look at the first psnqualid
record it finds and then stops:

SELECT m1.staffno, m1.forename, m1.surname,
CASE WHEN p1.cdelevelid = 1 THEN "D" WHEN p1.cdelevelid = 2 THEN "P" ELSE
"O"
FROM `master` m1
INNER JOIN psnquals p1 ON m1.staffno = p1.staffno

I also tried using an IF statement, but this also seemed to stop after
finding the first matching record in the psnquals table.

Get List Of Tables Containg Specific Records
I have a database with 20+ tables that contain data from various instruments. Samples can be measured on any combinaiton of instruments and I would like to be able to query the database to find which tables have data for a specific sample, with the table names being returned to build a dynamic web form for selecting and viewing data.

I can build sort of brut force queries via php to do this to mitigate re-writing webpages when additional tables are added, but it seems to me there should be an elegant solution (or at least brut elegant) to this.

Question About A Specific Query
imagine I've got user that can have visual preference (enabled or disabled) saved on a table.

Before a user make change of a preference, there is no row associate to that user and by default, the preference is enabled.

Now, is it possible to do a query that will output user that have preference set to enabled (those who have update their preference) while also outputing those who have no row in the table preference?

I know it may be not super clear, but I need to know before working on that script.

So here a sample to make sure it is all clear:

TABLE USER (id - name - email)

1 - NameA - a@a.com
2 - NameB - b@b.com
3 - NameC - c@c.com

TABLE PREFERENCE (id - label)

1 - Show warning
2 - Show help

TABLE USER_PREFERENCE (user_id - preference_id - status)

1 - 1 - Disable
2 - 1 - Enable

So if I want to output user email that show warning, it should give me:

b@b.com, c@c.com

My problem so far is, how to retreive user that have a user_preference row enabled, and user that have no user_preference row in the same query!





Query A Specific Day, And GROUP BY
The query below, counts how many records each agent has entered in the previous 7 days and groups them by agent...

Then it also counts a total for all the agents for the previous 7 days as well, not grouped.

How can i query a specific day of the week, say 4 days back, only count that days records and group them by agent?

Query For A Specific Amount Of Time...
I was wondering if there was some possible way to display a mqsql query for an exact ammount of time?

Query Result In A Specific Format
I need a query in which will give me a single column result
-----------------------------------
| [any column Name] |
----------------------------------
8:00 AM
----------------------------------
9:00 AM
----------------------------------
10:00 AM
-----------------------------------
11:00 AM
----------------------------------

I want the query to return a single column name with multiple rows in return ...

Average Number Of Records
Say I have 10,000 records, each with a UNIX_TIMESTAMP()'d date field, and want to know the average on how many records have been created each a 24 hour period for the past 3 months. How would I go about doing that?

I tried the following but receive a group by error:
SELECT AVG(COUNT(*)) FROM my_table WHERE date >= TIMESTAMPADD(MONTH,-3,FROM_UNIXTIME(UNIX_TIMESTAMP())) GROUP BY id

Find All Records With A Certain Number Of Characters
I have had a data problem where a field length has been truncated at 25 characters, rather than the 100 specified in the data type, varchar(100). I believe the problem to be on our website form input and not in MySQL (I didn't code the website, and I'm hoping the guy who did can correct the problem), but I would like to be able to find all the records that have been affected. Is there a WHERE statement that can find all records with at least 25 characters in a particular field?

How To Join On Unknown Number Of Records?
I have the following data in my database.

ID    | Name  | Relation/Value
-----------------------------------------
 26   | PPID  | DMDR_14
 26   | PPID  | BMDR_20
 14   | DMDR  | DMDR_16
 16   | DMDR  | BMDR_33
 16   | DMDR  | BMDR_52
 33   | BMDR  | Here is the result
 20   | BMDR  | BMDR_10


In other words, PPID 26 points to DMDR 14 and BMDR 20. DMDR 14 points to DMDR 16 which in turn points to BMDR 33 and BMDR 52. BMDR 33 does not point to anything. Its the bottom of the chain.

I can keep joining the PPIDs to the DMDRs and the BMDRs to get to the bottom of the chain. My problem is that I don't know how many DMDRs or BMDRs the PPID goes through so I can't just keep adding another join. Is there a simple way to solve this using a loop or something perhaps? Code:

Select Lastest Input To Data Base And Select Ordering From Last Member To First Member, Limiting Output Diplay To A Specific Number
how to display the latest members that signup to website, a query that that can select ordering them base on the last registered member to the first... then limiting output by say 50 members.

a sql statement that can select lastest input to data base and select ordering from last member to first member, limiting output diplay to a specific number

MySQL Admin - Lost Thread On Specific Like Query?
mySQL win32 (4.0.22)

I am using mySQL Control Admin and seeing a lockup on a thread specific to a
like query.

select * from table1 where field1 like 'http://h%' limit 100
This request will sit (thread) forever and never return any records. (status
: sending...)

However : select * from table1 where field1 like 'http://h%' limit 100
returns records immediately, no problems...

I have already run : /mysql/bin/myisamchk --sort-recover dbtable1, no
errors, no problems...

How can I tell what this thread is really doing or if any additional
problems exist with this table using myisamchk?

Extending Simple Query With Specific COUNT() From Second Table
Currently i basically do following:

-----------------------------------
SELECT cat_id, cat_name FROM categorytable WHERE blah=something ORDER BY pos ASC

while(FetchRowAssoc())
{
SELECT COUNT(*) as itemcount FROM itemtable WHERE category=cat_id

echo cat_it, cat_name, itemcount, blah... etc.
}
------------------------------------

I fetch some info from the category table and then I want to know how many items I have in the 2nd table which are associated to the categories in question from the first table.

Can this be done with a single query statement, so i get from FetchRowAssoc the cat_id, the cat_name and the count of the items for this category?

"SELECT t1.cat_id, t1.cat_name, COUNT(t2) as itemcount FROM categorytable as t1, itemtable as t2 WHERE t1.blah=something ORDER BY t1.pos ASC " <- like this but working, i really don't get how to properly write the syntax there... also didn't found a useful example with googling.

Counting The Number Of Records That's Greater Than The Limit
I have a table that has thousands of schools in it. I'm returning all the schools in a certain state. I'm limiting it to 20 per page. However, I want to display text that says how many there actually are...exampe: 'showing 1-20 of 43'.

Is this possible? My query is below:

SELECT id, city, CONCAT(school_fname, school_lname) AS thename FROM ccn_schools WHERE state='KS' ORDER BY CONCAT(school_fname, school_lname) LIMIT 20

So how do I have to run this query without a limit to get that number?

Join Tables To Count Number Of Records?
I've two tables:

responses
==========
response_id
schema_id
timestamp

answers
==========
answer_id
response_id
answer

(that's a cut down version, but will do for this question)

I need to get all the responses where there is at least one answer in the answers table. But I do not want the answer data. It's literally a quick check for an export to say "get me all the responses where there's at least one question answered". I have this: Code:

Administrator Rows Vs Actual Number Of Records
I imported some table (about 1500 records) using "LOAD DATA LOCAL
INFILE..." (command line console). No warnings, no skipped, no deletes
- all the recored are written to be imported.

However, in MySQL Administrator UI tool I see completely different
number in the "Rows" column. Making a SELECT query shows that the
actual number of records in the table is the correct one (the same
number as in text file table). Command line SHOW TABLE STATUS FROM ...
doesn't show any of these numbers.

I would expect that the "Rows" column doesn't show the actual number of
recored. But, the information about of 100 enteries table is shown
correctly (rows=records=100).

Retreive First Characters
I have a field in my database called "description" (type:longtext) and I would like to retreive the first let's say 13 characters. What wold the select query be?

Retreive A Static Value
I am trying to retrieve members team values from one table "members" which are all values from another table "parameters" when inserted, with one exception (one value) this is a static value in a drop menu/list called & has the value of "Any". My sql statement works fine & spits out the correct team name or values until I come across the odd static one that was inserted "Any". i am asking for members prefered team & thats where any comes in & the retrieved value is always blank when I come across it, I know why it's blank but not how to fix or add to my statement. I have found a little help here but it's more about insert, could someone assist me with the following statement to say if it's not one of the existing values then (php) echo "Any".

SELECT members.mem_prefered_team, `parameters`.parameter_team_name
FROM members, `parameters`
WHERE member_id = colname AND members.mem_prefered_team = `parameters`.parameter_id

Cannot Retreive Images From Database In Os X
I am unable to retreive image files from a mysql database using IE 5.2
on the mac OS X platform.

I have built a database driven website that stores images as blob
files. I specify the mime types and limit the file sizes to 15k.

I can retreive the images using Windows, and Mac OS 9, but explorer
running on OS X cannot retreive the images but can return textual
data.

Retreive Table Structures
with what syntax can I retreive the sql-structure-code of an existing table?

Retreive Last Inserted Record
is it possible to retrieve the last row which was inserted?
e.g., I insert a record like this:

"INSERT INTO SONG (Songtitle) VALUES ('purple rain');"

what I need then is the ID (fieldname: sID) of that record, I could retreive it like this:

"SELECT sID FROM SONG WHERE Songtitle = 'purple rain';"

is there a saver method? I mean, no matter what reasons, 'purple rain' could already exist in another record, then I might get the wrong sID.

Retreive Only Numeric Data Types
how to return colums that are numeric from a table?

C Api Calls To Run Stored Procedure/retreive Results
Can anyone give me an example of calling a stored procedure with
parameters and getting back the results? I can't find anything in the
docs that talks about calling stored procedures.

C Api Calls To Run Stored Procedure/retreive Results
Can anyone give me an example of calling a stored procedure with
parameters and getting back the results? I can't find anything in the
docs that talks about calling stored procedures.

Number Of Replies Query
I have a forum using parent id and qid(auto increment). Parent id will be set "0" if this is a new thread, otherwise, parent id = qid (reply).

In my index page, I can read the parent thread just as usual using select * from forum where parent id = 0 order by last update date.

But I want to know how do I also display the num of replies to those replies also.

I am using a while loop to generate the parent thread as

while ($row = $result->fetchRow()) {
echo"$q_id = $row[0];";
echo"$forum_type= $row[1];";
echo"$user_id= $row[2];";
echo"$title = $row[3];";
echo"$body = $row[4];";
echo"$last_upd_date = $row[5];";
}

Setting Number Format In Query
This might be an easy one, but I can't seem to find how to do this. I'm computing an average in a query, and I need to format the result for display in a php generated webpage. The values being used for calculating an average are real(4,1), but my average comes out with a precision of 5 decimal places. I'd like to show only 1 decimal place.

Query Fields That Start With A Number
I am building an index for our Client List page, which lists over 400 clients of ours.  I want to change the SELECT query that returns the resultset that is shown to select ONLY records that start with a certain letter.  This is being done with the addition of the following code to my MySQL query:

$query_Clients .= "WHERE clientName LIKE '".$_GET['letter']."%' ";

Get Category And Number Of Items In One Query
I have a `category` table with columns cat_id and cat_name. And another `items` table with columns item_id, item_name and cat_id. I want a query which will select display each category name and the number of items in that category. I could do this in two sql
statements, is it possible to do it in one?

Using A Query To Determine The Maximum Value A Number Col Can Hold?
I'm trying to find out how can you determine the largest value you can enter into a column of type smallint,mediumint,int, etc using a query. I know what the values are by looking at the documentation, but I would like to get this number using a query at runtime. So when I insert values into different tables/columns I can use an appropiate restriction befor trying to insert.

Trying To Count The Number Of Rows In A Result Set After Query
The user fills out this form to sign up to the website, the form checks the database to see if the username has already been taken with the code:

$conn = mysql_connect("localhost:3306", "root", "********")
                                    or die ("Error With Connection");
        echo("connected<br><br>");
        $db_sel = mysql_select_db("game",$conn)
                                    or die ("Error With Database");
        $check = "select * from users where 'username' = '$username'";
        $db_sel = mysql_query($check,$conn)
                or die (mysql_error());

Does Query Speed Depend On The Number Of Coloms?
Does the query speed also depend on the colums that you don't use in the
query (so not in the where and not in the select part).

I have a lange unused backup field in every row.
I only put the backup information into that field once.
But never use it on my live database.

Does it speed up my queries if I put the backup information into an other
table?

Find Hightest Number After Finding First Query
i have this code but it does not display the highest number or anything.

it should be searching the field 'name' for the string $name and only display the one that has the highest number in the 'number' field.

what am i doing wrong?

$res = mysql_query("SELECT MAX( number) FROM data WHERE name='".$name."'");
$high = mysql_result($res, 0, 'number') or die(mysql_error());
echo($high);

Deleting Records Upon Query... (!?!)
Sorry for the confusing thread title. Here's what I am trying to do...

Read the last six added records for a particular criteria, and delete the rest. Now consider I have around 1000 unique "criteria" and this query is executed a few times a day for each unique... should I delete it on each read or put it in a cron job and schedule it for every night.

Here's a sample MySQL syntax for my selectquery:


SELECT * FROM table1
WHERE field1 = sometext
ORDER BY some_time_field ASC
LIMIT 0,6
So the questions, again, are:Can I join this SELECT query with a DELETE, and delete all field1s with "sometext" which were not selected by the query?If I can't, how would I do it with a seperate DELETE query? i.e. Leave the last six records for field1 = sometext and delete the rest?Do I really need to order by some_time_field? Or does MySQL have an internal schema to sort records by their "internal" creation date?

Query Help Looping Through Records
The below Query loops through two tables in mysql and outputs all records where a match_date in a reports table (re) is equal to a match_date in a fixtures table (f).

Now this works well, but what I want to do is say to my query is find all of these dates BUT

- As soon as the FIRST f.date is found that does not have a re.date matching it output that information and limit it to 1 .....

Count Records Within Query
I have the following information in table 'Test1':

field1  field 2
000001  000000
000002  000001
000003  000000
000004  000000

I want to write a query that will only display the unique field 2 records and as well provide a count of how many records have that id.

output should look like

field2  recno
000000    3
000001    1

can some one help with the trick to make this work?

Query Cannot Retrieves All The Records
I've got this problem, this query is used to create a combo wich display all months where at least a news is been submited (a kind of hostory menù), the fact is that it can display max the months wich correspond to the 107 record submited.

The query:

select date_format(data,"%b/%Y")as textMonth, month(data)as month,dayofmonth(data)as day,year(data)as year from archivio where category = "Rassegna Stampa" group by month

Just to be shure I've also tried the query above on mysql browser, and the result is the same. Can you tell me if there's a kind of limit?

Query And Non Existent Records
I have a mysql table texts which keeps textlines in different languages.

columns: textId, languageCode, textline

The application adds records for specific languages as:

textId 1
languageCode: EN
textline: "Username"

another record could be:
textId 1
languageCode: DE
textline "Anwendername"

Now at a certain pojnt in the app I have to check whether for a specific textId there are textline filled in for specific languageCode. For example: Is there a textline for records with textIds 120, 124 and 134. And are these records present for EN and FR (French). I can query as:

Select count(*) from texts where textline != '' and textId in (120,124,134);

But what when the records are there in ENglish and German but not in French?

Any ideas how to solve this?

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

Total Like Records Query
Ime probably missing the boat here so please be patient. I am trying to create a query to display the total number of records with the same parent name.
Eg
Total records for author Eddings = 10

So in effect i want to count all the entries and display only the numeric figure of books for that author. I think its supposed to look something like:

Select
sum(Eddings) $total
From books

Query Total Records In 1 DB With 5 Tables:
In PHPmyadmin there's an option that shows you the amount of records in all tables, how can I did this via a query?

MySQL Query For All Records With NULL Value
I have recently been trying to extract a few products from a database (that is quite big), so that I can find products that have a specific NULL Value, what kind of a SQL statement would allow me to do this?


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