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




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?




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Sql Query For Count Records Of Current Week
I have a registration form that saves the registration date on a datetime column. I would like make a query to know how many records are in the table that where for the current week. For example, I'm on week 25 and I want to know how many records I have for this week without the need of specifying the from and to dates. Is there a way to do this?

Count Related Records, But Show Records With NO Related Records Also
cl_items
========
it_id (pk)
it_ownerid
it_name

cl_offers
========
off_id (pk)
off_itid (fk) -> to it_id
off_whoid

My query needs to output ALL of the records in cl_items AND still show how many offers are on each item (from cl_offers)

I can't get what I want through the GROUP BY because I want to show the records in cl_items which DO NOT have any offers on them yet also.

Is there any way to do this with mysql only?

Count Records Per Day And Show Max
I've been using basic sql for a while and always used PHP to get round
complicated queries but now I need to see if I can create a query that
will show me the busiest day in our helpdesk and return the date and
the number of calls.

We have a database with a table called tracking which has date fields.
I want to count all teh records for each day, and return date with the
highest count and the count itself...

I'm sure its possible but I'm stuck as to what to google for...

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

Count Records From Two Tables
I have two tables and I want to count the number of records where field1 = 1.

tbl1    field1
           1
           2
           1
           0

tbl2    field1
           0
           0
           1

Result should be 3

Can someone help with the right coding?

How Do I Do A Count Of How Many Records Are Tagged Under One Tag?
How do i do a count of how many records are tagged under one tag?

SELECT DISTINCT ut.uxtagid, ut.uuserid, ut.uprivate, tt.tid, tt.ttag, tt.trated FROM usertags  ut, thetags tt WHERE ut.uuserid=1 AND ut.uxtagid=tt.tid ORDER by tt.ttag

"thetags" contains the actual tag name like this:

tid, ttag

"usertags" when a user tags a record its stored here, and the records here are linked to the tag name

uuserid = the user who tagged it
uxtagid = is joining the "thetag" table to identify the name of the tag
uxforumpostid = the record that is being tagged

How Count Records From Two Tables?
I’m having two tables: ap_author and ap_books. I wont count how many records have everyone authors in table ap_books.

ap_author ------------------------------
| author_id | first_name | last_name |
| 1 | first1 | last1 |
| 3 | first2 | last2 |
| 4 | first3 | last3 |
--------------------
ap_books-------------------------------------
| book_id | title | author_id | total_pages |
| 1 | title1 | 1 | 2 |
| 2 | title2 | 1 | 5 |
| 3 | title3 | 4 | 1 |
--------------------

I use this query: SELECT ap_author.author_id, ap_author.first_name, ap_author.last_name, COUNT(*) AS books FROM ap_author, ap_books WHERE ap_author.author_id=ap_books.author_id GROUP BY ap_author.author_id

This query returns only these authors, which have one and more records in table ap_book. How I’m can get all author?

Count And Arranging Records
I need counting the number of records each user has and arranging their outputs.

This is my sample table:
uname | uid
-------------
"bob""1"
"bob""1"
"bob""1"
"james""7"
"james""7"
"lars""11"

I'm trying to select the uname and uid from this table based on which users have the most records in there.

So in this case the output would be

"bob""1" "3"
"james""7" "2"
"lars""11" "1"

Bob will be top since he has 3, james will be next and so on. The 3 2 1 you see is the number of records each has.

Count Deleted Records
Is there a way I can count/display the number of records affected by a delete statement on my webpage.
I currently have a delete statement:
DELETE FROM applications WHERE Date < whenever

can I combine this with a COUNT ??

Get List (count) Of Records
I want to get a list of records with duplicate (or triplicate, etc.) fields.
I tried:

SELECT *, count(*) as q FROM test WHERE q > 1 GROUP BY field1;

This didn't work because "q" is regarded as a missing column. Is there a
way to do this in a single SQL statement?

Compare Count Records
I need some help with some SQL I need to write.
Here is what I'm trying to do:
I have 2 tables in the same format. Table B is a subset of Table A.
For each key value I need to count how many records I have in table A and in table B and output the entries that are missing from table B.

E.g. for key 100 table A has 5 records and table B has only 2.
I need to output the missing 3 records.

Get Count Of Matching Records
I have two tables, that I am trying to match up rows and count the number of times first_name AND last_name in table A match first_name AND last_name in table B. What is the best way to do this without creating a mess of queries and code?

Getting A Count Of Records Based On Inner Relationships
I am making a PHP-MySQL forum. I have a table "forum" that holds all the posts.

Fields in forum: ID, user, title, body, threadID, datePosted.

All top level posts (ie, original posts for a thread) have a threadID=0. All other posts are comments, hence their threadID is set equal to the 'ID' of the original thread post.

I can get a list of the last 10 top level thread posts:
select * from forum where threadID=0 order by ID desc limit 0,10;

Also, I can get the # of comments for an individual thread (for instance, thread # 37):
select count(*) as Expr1 from forum where threadID=37;

How in the heck do I form those two statements into one statement? In my main forum view where I list the last 10 threads, I want returned in each result set the ID, title, user, and the # of comments posted in that thread.

Select / Count Not Showing Records ... Permissions?
I imported 600,000 records from SQL Server 2005 to mySQL.

I know they are in there -- I just can't see them!

When I do a SELECT, it processes for a while, and then returns nothing.

Same with a count, it sits there processing, and then returns a '0'

However when I do the same on a table I know has no rows, it definitely
comes back right away.

I'm logged in as root. Do I need to assign myself some permissions to
see these records? And the count numbers?

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:

Wot Is The Function To Count The Records In Selelct Statmtn In MySQL
wot is the function to count the records in Selelct statement in MySQL?

Just like
PHP

mysql_num_rows($result);

in php.

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

This is my query:

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

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

Select Query With Sub-query For Count And Max
I have a table "test"... as below... I want to have a result set of all the parents with the count of their children and the lastest created date of their child ...

SQL Count Query
I have 3 tables:

j_photoparent (holds photo "parent" e..g "nature", "places")
j_photocat (holds photo categories, e.g. "leaves", "snow", "london eye")
j_photosmaster holds photo details

The keys are as follows:

j_photoparent.parentID
j_photocat.catID
j_photocat.parentID
j_photosmaster.photoID
j_photosmaster.catID

I have a simple SQL statement to randomly select a photo category:

SELECT jpc.catID, jpp.parentID
FROM j_photocat jpc, j_photoparent jpp
WHERE jpp.parentID = jpc.parentID
ORDER BY RAND()
LIMIT 1
What would be great though, would be if I could combine the SQL above, to also count how many photos in the "j_photosmaster" table for each randomly selected category.

Could it be done in the same statement - or would I need to do two - the first one above and then this one:

SELECT COUNT(*) FROM j_photosmaster
WHERE CatID = &catID_FROM_ABOVE
Could it be done with a sub-select?

Help With Query Using Count
I have the following query, but for some reason I can't seem to get the price count part to work.

What I want to do is the get the max and min price for each indivdiual product and I then want to count how many products of the same where found with these different prices.

The only problem is that the count part seems to be giving me the wrong totals.

For some it is giving me 783 when there is only 2 of the same products.

Here is the query that I have.

PHP

select ides,merchantes.merid,merchant,price,min(price) as minprice,max(price) as maxprice,count(price) as pricecount,rand3,title,imageurl,brand,description,pm from merchants,prodsearches where prodsearches.merid=merchants.merid and app=&#391;' and match (brand,category) against ('"games"' IN BOOLEAN MODE) group by brand,category order by random2 asc

Query Count
I've seen on some sites that there is a way to total up the number of queries ran on a page, and the time it took to run them - as per the bottom of this page:
Is this something which can only be done using PHP, or could I achieve the same result using ASP, by accessing something within MySQL?The reason I ask is that I have a site running MySQL on a Windows server, running IIS and ASP, and would like to set something up like the above.

COUNT() 2 Tables In 1 Query
So I have these two queries:

$result= mysql_query("SELECT YEAR(add_date), MONTH(add_date), COUNT(*) FROM clogsyn_track_main where user_id='$uid' GROUP BY YEAR(add_date),MONTH(add_date)");

$result2= mysql_query("SELECT YEAR(add_date), MONTH(add_date), COUNT(*) FROM clogsyn_track_pop where user_id='$uid' GROUP BY YEAR(add_date),MONTH(add_date)");

They output data like
Month Year, Total Views
So I can see how many total times a page was visited that month for a specific user_id.

The problem is I'm tracking 2 sections of the site "main" and "pop" which pop is a unique page that pops up when something is clicked.

I tried EVERY way to join them together but the count(user_id) doing a LEFT JOIN kept adding the count()'s from both tables together.

Is it not possible to do a count() on two tables in 1 query?

Here's one of the many combined I tried.

$sql = "SELECT a.user_id,b.user_id,YEAR(a.add_date),MONTH(a.add_date),COUNT(a.add_date),COUNT (b.add_date) FROM clogsyn_track_main a LEFT JOIN clogsyn_track_pop b ON a.user_id=b.user_id AND YEAR(a.add_date)=YEAR(b.add_date) AND MONTH(a.add_date)=MONTH(b.add_date) WHERE a.user_id='$uid' GROUP BY YEAR(a.add_date),MONTH(a.add_date)";

Can anyone help me here or is it not possible to do it in 1 query?

Query To Return Two Count()s
I'm trying to figure out a better way of doing this:
SELECT
(SELECT COUNT(*)
FROM GuestEvents
WHERE EventID = 1
AND EventStatus = 'y'
AND UserID = 'bob')
AS Event1,
(SELECT COUNT(*)
FROM GuestEvents
WHERE EventID = 2
AND EventStatus = 'y'
AND UserID = 'bob')
AS Event2
As you can see it's quite repetitive, I wondered if there isn't something like this which could optimise it a bit:

SELECT COUNT(EventID=1) AS Event1,
COUNT(EventID=2) AS Event2
FROM GuestEvents
WHERE EventStatus = 'y'
AND UserID = 'bob'


WHERE COUNT MySQL Query
PHP

$queryA = " SELECT soundcard_co, soundcard_model,  count(soundcard_model) as count_model, AVG(value_num) AS value FROM reviews GROUP BY soundcard_model ORDER BY value DESC LIMIT 10";


Okay, there's my MySQL query.

I have a crappy little review script that lets people review home recording sound cards. This script will display 10 sound cards with the highest average score for overall value.

As you can tell, this selects the the company, model, and average overall value rating of sound cards that have been reviewed on my site. It puts them in descending order and limits the results to the top 10.

I've found that these results are easily skewed when a particular sound card gets only one review. I don't want a single person to have the power to put a sound card on top of my ratings. So, I want to select sound cards from the database that have had at least 3 votes.

While I could come up with a php solution, I'd prefer to use MySQL.

I have tried this:

PHP

$queryA = " SELECT soundcard_co, soundcard_model,  count(soundcard_model) as count_model, AVG(value_num) AS value FROM reviews WHERE COUNT(soundcard_model)>2 GROUP BY soundcard_model ORDER BY value DESC   ";

But I keep getting a "Invalid use of group function" error.


Count Query Problem
I want to count users by their status, following is the code which I am using currently, instead of using four queries I want to convert this code in one query....

Count Different Distincts In One Query
Any way to count different distincts in one query?

Sub-queries not supported in my MySQL v4.0.??

I have this:

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

Make A COUNT Query
I want to run a query on quite a big table, about 3,000,000 records.

The query is quite simple
SELECT COUNT(*) FROM TblName WHERE Something = 1
I am only interested to know whether there are at least 10,000 records that meet this condition, so counting the whole table and then comparing the result to 10,000 is overhead. Is there a way to write a query that would simply tell me if there are at least 10,000 (or any other number) records, and would stop executing/counting once it gets to 10,000?

Query Count Return Zero
I'm trying to query a database searching for everytime an event happened in the past 24 hours. I'm using a count(eventid) to add up each event during an hour time.

However, if an event didn't happen say for 2AM then 2AM isn't shown in the return.

How can I get 2AM to show as a row, but with a count of 0 (zero) ??

Here is my qeury...

select count(eventid), DATE_FORMAT(CONCAT(eventdate,' ',eventtime),'%Y%m%d%H') as hour, time_format(eventtime, '%H:00'), eventdate from event where sensorid = '2' and eventdate between '2005-01-19' and '2005-01-20' and DATE_FORMAT(CONCAT(eventdate,' ',eventtime),'%Y%m%d%H%i%s') >= '20050119150018' group by hour order by hour desc;

MySQL Query COUNT
I need to create a sql statement that queries a mysql database for the top x amount of entries that include their name. Basically the site logs everytime they upload a file, and I want to see which users have the top number of uploads. Any ideas? Thanks in advanced to any help.

Table:

fileid
filename
submittername
submitterip
fileinfo
filetype
date

Help With Query: Order By Association Count
Allright, here are my tables:
Posts:
id | title | text
Comments
id | post_id | name | comment
Basically one post may have many comments. Now, how would I select the 10 posts with most comments, and if only 5 posts contained comments (but there are in fact 10 posts) how could I make this query still return a total of 10 posts?



Select Query With Character Count
can you help me with creating a select query where the character count in a specific column is more than, say, 20 characters?

SQL Query To Include Count From Associated Table
I am having a tough time coming up with the sql for the statement but the long and short of it is this:

Two Tables:

Table 1 is a group - Table 2 is a list of items that belong to a group from table 1.

I want to query all (*) information from table 1 AND get the count of the number of associated items from that group from table 2 in that same query.

Retrieve Everything AND Count Rows In One Query
set rsminmax = con.execute("SELECT * FROM `minirules_minmax` where RuleId = '" & contractId & "'")
set rsminmax2 = con.execute("SELECT COUNT(*) FROM `minirules_minmax` where RuleId = '" & contractId & "'")


Is there any way to do this in one SQL query?

First Group By Date, Then Count... All In One Query?
I have a mySQL database that has individual records for each time a page on my site is hit. What I'm trying to do is set up a tracking system which will display the hit counts for each page, by month, for the past three months, and ordered by total hits over that timespan.

The table is simple:
visitedPage | visitedTime

My current query is this:

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:

Count The Hits For Week And Month In One Query?
I have this query to count the amount of total clicks for a whole week, but i would also like to know the total amount of clicks for the whole month. Is it possible to do both of them with one query? Or do i really need to make 2 seperate querys for that?

SELECT date FROM clicks
WHERE date >= '$timestamps[0]' and date <= '$timestamps[6]'
AND link_id = '{$row['ad_linkid']}'

Preventing A Count Query Inside A Loop How?
I have an idea in my head and im pretty sure its possible but I don't have enough mysql knowledge to apply. Basically, I have this:

SELECT user_id FROM ml_group_subscriptions WHERE user_group = $id
then in php I initialise a loop go over the results:
PHP

while ($row = mysql_fetch_array($get_users))
                {
                    $this_user = $row['user_id'];


and then an insert query:

INSERT INTO ml_subscriptions (`user_id`, `campaign_id`) VALUES ($this_user, $add_to_campaign)
while this is all dandy, I don't want duplicate data. My only current method would be
PHP

$get_users = mysql_query("SELECT user_id FROM ml_group_subscriptions WHERE user_group = $id");
                while ($row = mysql_fetch_array($get_users))
                {
                    $this_user = $row['user_id'];
$check = mysql_result(mysql_query("SELECT COUNT(user_id) FROM ml_subscriptions WHERE user_id = $this_user"),0);
if ($check == 0) {
                    $insert_users = mysql_query("INSERT INTO ml_subscriptions (`user_id`, `campaign_id`) VALUES ($this_user, $add_to_campaign)");
}
                }


as you can see this is putting a query inside a loop which could be potentially huge. Can I not adapt the first SELECT query to only accept data that is not about to be duplicated?

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());

How To Improve The Speed Of Mysql Query Using Count(*)
I'm using this kind of queries in mysql in InnoDB engine

Select count(*) from marking1 where persondate between '2007-04-23 00:00:00.000' and '2007-04-23 23:59:59.999' and PersonName='aaa'

While executing these queries from front end VB, It takes above 5 secs with 50 thousand records.

How can I improve speed for this kind of queries. Is there any alternation for this command.

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

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 The Article Table And Get A Count Of All Related Comments
Could someone please help me with this query. I have two tables -- one for my articles and another for my comments. Comments are stored in the comments table with a corresponding article id.

I want to query the article table and get a count of all related comments. The following query doesn't seem to work for me. Can you please suggest how I fix it?

SELECT a.id AS id, a.title AS title, a.preview AS preview, a.thumbnail AS thumbnail, a.category AS category, a.timestamp AS timestamp, a.game AS game, count( b.id ) AS commentcount
FROM article_table AS a, comment_table AS b
LEFT JOIN comment_table ON a.id = b.article
WHERE a.news = 'Yes'
AND a.type = &#391;'
AND a.saved != &#391;'
GROUP BY b.article
ORDER BY a.timestamp DESC
LIMIT 5

Count One Table's Rows From Multi Table Query
here are my tables (condensed)

FEEDS
feed_id
site_id

SITE
site_id
site_name

ARTICLES
article_id
feed_id
link

I want to create a query that returns the total number of articles for every site_id (which is unique in the SITE table). I have this:

PHP

$gsite = mysql_query("SELECT site.site_id, feeds.feed_id, COUNT(articles.article_id) AS acont FROM site,feeds,articles
WHERE feeds.site_id = site.site_id AND articles.feed_id = feeds.feed_id group by site.site_id", $connection)
or die(mysql_error());

The query does not use JOIN, ON and all that good stuff.

I just need the following variables to run through a loop:

site_id
the number of articles rows per site_id

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.


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