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




Count(*) In A Select Returns "1". It Should Behave Like Select Count(*)


i'm trying to make a query work properly but I got lost:

SELECT *,count(*)
FROM cancons c, musics m, discos d, r_discos_cancons rdc
WHERE c.c_id_music = m.m_id
AND rdc.rdc_id_disc = d.d_id
AND d.d_id_music = m.m_id
AND m.m_id = 24
GROUP BY c_id

note:
cancons (ca) = songs (en)
discos (ca) = cd's (en)
music (ca) = musician (en)

don't worry for the WHERE part. i need it because of the foreign keys.
this query returns a table with the title of the song and some more data. on the right side, I get another column called "count(c_id)" with the number "1" in it for each row. That's supposed to be due to the "group by" clause, I think.

I'd like to get the table with the songs, as usual, and, with the same query, I'd like to get the total number of rows selected.




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
About "Select Count(*)" Always Returns 0.
my mysql version is:

Ver 14.7 Distrib 4.1.14, for pc-linux-gnu (i686) using EditLine wrapper

OS: uname -a
Linux backup_srv1 2.4.29 #4 SMP Thu Mar 24 10:31:26 CST 2005 i686 unknown unknown GNU/Linux

Desc:

My statement is
"SELECT COUNT(1) FROM t_card_info_035 WHERE Fcommodity_id = 0x1111 AND Fseller_uin =111111 AND Fdeal_id = 12345;"

my client is a daemon, when it started, it can return the correct result, (such as 4 ) but after two or three days later, it always returns 0. I had gdb into it and find that the result in the result row is 0. but when I restart my daemon program, it will be ok again. This made me crazy... it is a mysql c API bug or something else?

My daemon client is programmed by c++ , and use the c API to connect mysql. I had check that there is nothing wrong with my code, and it has no memory leak or somthing else.

Count(*) Returns "Resource Id#3"
I have table:

CREATE TABLE users(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
nick varchar(32),
passw varchar(32),
email varchar(128),
email_poskytovatel varchar(64));

and I want to read variabile id . I am using command SELECT Count(id) FROM users. But it returns "Resource id#3". Where is my problem?

How To Fix "Column Count Doesn't Match Value Count At Row 1" ?
I've been trying to install a portal to my installation of Invision Power Board, and I keep coming up with this problem. I post here for two reasons: firstly is that no one is responding over at the portal creator's thread and I need help, second is that this error looks like a mySQL error that could be solved without the need of the creator if possible.

Here is the error returned:

mySQL query error: INSERT INTO `ibf_portal_box` VALUES (1, 'lang.last_topics', '<box><menu>10,20,30,50</menu>
<topics_show>10</topics_show>
<order>last_post</order>
<exforums></exforums>
</box>', 0, 'middle', '*', 0, 4, 'last_topics', '1')

mySQL error: Column count doesn't match value count at row 1
mySQL error code:
Date: Tuesday 21st of December 2004 08:43:10 PM

I am very new to mySQL and don't really understand it. What is wrong with the above that it is trying to insert, and how is it fixed?

Count Query Causing &quot;excessive Processor Usage&quot;
For the second time in the past 6 months my hosts have shut down my site because it was apparently causing a shared mySQL 5 server to max out at 100% usage. I'm not much a programmer, know even less about mySQL and obviously don't have access to the server from the back end but I'd appreciate any advice as to whether it is my query that is causing the problem:

Set rsMail = objConnC.Execute("SELECT * ,(SELECT COUNT(*) FROM comments WHERE comments.submissionID = submissions.submissionID AND comments.commentInclude = 1) as CommentCount FROM submissions WHERE PigeonHole = 'mailbag' AND Status <> 'hold' ORDER BY submissionID DESC LIMIT 20")

Apart from two instances, this query has been working fine on a page that receives between 10,000 and 30,000 visits a day.

The site is running on Windows and coded in ASP but is calling a separate mySQL server.

"Select * FROM" Vs "Select Field1,field2 FROM"
No matter how many fields I want to retrieve from the table I always use "Select * FROM Table" instead of "Select field1,field2 FROM Table".

Are there any disadvantages of always using "Select * FROM Table"?

Count User Comments In Each Category (was "help On A Query")
I would really appreciate if someone could help me out on this one. this are my tables:

comments

Comment_ID
Video_ID
Comment_Text
Comment_UserID
....
video
Video_ID
Category_ID
.....
category
Category_ID
Category_Name

I'm trying to get a user's count of comments for each category, ordered by the number of comments DESC. basically, I want to show the top categories where the user has posted the highest number of comments.

so far this query gets me the category name of where the user has posted:


PHP

$SQLTemp = "SELECT Category_Name
            FROM category
            WHERE Category_ID
            IN (
            
            SELECT DISTINCT (    Category_ID        )
            FROM video
            WHERE Video_ID
            IN (
            
            SELECT DISTINCT (    Video_ID        )
            FROM comments
            WHERE Comment_UserID = $id
            )
            )";

THANKS!!

Count Of *unique* Visits By Page For Each Day (was "Need Help With Query")
Using MySQL 4.1

I have a table 'orders' with the following fields:
ipaddress
pagenum
xtime (which is just the yearmonthday)

this is the query:
SELECT distinct pagenum,ipaddress,xtime,count(pagenum) AS pagenumtotal FROM `orders` group by pagenum,xtime ORDER by xtime, pagenum asc

What I am trying to do is return a count of *unique* visits by page for each day. This query returns a count of *all* visits by page for each day, including repeats. So if a visitors hits a certain page on the site 10 times and adds a record 10 times, the count result will include all 10 records in the count. I want this to only count as 1.

Relations In &quot;CASCADE&quot;, &quot;SET NULL&quot;, &quot;NO ACTION&quot;, &quot;RESTRICT&quot;, &quot;--&quot; ?
what do they mean to set the relations of a Foreign KEY in "CASCADE", "SET NULL", "NO ACTION", "RESTRICT", "--" ?

Add COUNT(*) To Already Existing Query (was "How To Do This")
I have this query:
PHP

SELECT entries.*, categories.*, uploads.*, entries.blog_id FROM entriesINNER JOIN categories ON (categories.category_id = entries.category_id) LEFT JOIN uploads ON(uploads.blog_id = entries.blog_id) LEFT JOIN images ON (images.blog_id = entries.blog_id) ORDER BY entries.date_submitted DESC LIMIT 3

Now i want to add this
PHP

SELECT COUNT(*) FROM comments


but i dont know how to add it into the already existing query. The messages table has a column blog_id column in it so i could do a join like thisd LEFT JOIN comments ON
PHP

(comments.blog_id = entries.blog_id)

but i dont know how to get the first bit in there



"Warnings" Count When Using Mysqlimport
When using mysqlimport, the final statistics include a count of
"Warnings", for example:

Connecting to foo.whatever.com
Selecting database foo
Loading data from LOCAL file: foo_userInfo.imp into foo_userInfo
foo.foo_userInfo: Records: 248 Deleted: 0 Skipped: 6 Warnings: 248
Disconnecting from foo.whatever.com

I'd like to know what the warnings were, however there doesn't appear
to be a command line option that might be used to expand the statistics
or otherwise output the text of the warnings (--verbose does not do
it).

Is there any way to view the warnings?

Get Average Of A "count"
How to get average of a count(user);
Following syntax run very well
$records = mysql_query( "SELECT user,action,count(user) FROM log where date='$datetr2' and action='add' group by action,user")

But now I also want avg(count(user)), but it didn't work

$records = mysql_query( "SELECT user,action,count(user) ,avg(count(user)) FROM log where date='$datetr2' and action='add' group by action,user")

count(user) only get hot many times a user log into the webside a day. Right now I want to know the average times of user logging into the web within month. I don't know to get average number. avg() function doesn't work here.

How To Modify The &quot;select&quot; Function In The Source-code-version?
I have a source-code-version of MySQL at hand,and I want to modify the "select" function to optimize it.

The question is:how can I start? I wonder whether "select.cc" is the right file I can edit.

Single Query For No Of Hits &quot;Today&quot;, &quot;This Month&quot;, &quot;This Year&quot;
Is it possible to construct a single query that fetches the no of pageviews "today", "this month", "this year" and "total since start"?

The table is very simple, one field for Date (YYYY-MM-DD) and one for the no of pageviews this day.

If not, would it be much slower/faster to divide the query into 4 different queries?

Can You Select And Concat Multiple Items Separated By "," ?
The select I have finds multiple values for a field. I want to take that field and create ONE field separated by commas.

Is that possible? I could do it in PHP but it will be easier programmatically if I can do it here.

For example:

HTML
Select field1 where x=2;
val1
val2
val3
val4
I want it to be like:

HTML
Select field1 where x=2;
val1, val2, val3, val4
where "val1, val2, val3, val4" is ONE field I can then use.

I am actually using this as a subquery so it's not as easy as php's explode/implode.

First And Last Time In Each Date By Empl (was "Help Me With This Select Statement")
I have the following table which has the following fields:

logid, empid, transdate,transtime

I want to select the first and last transtime in a specific date for every employee, how can i do that?

Dates In The Past 3 Weeks (was "SELECT Query Help")
I'm trying to select data from a table that has been submitted in the past 3 weeks. I am not having any success.

Bugzilla: MySQL Returns "Got Error 127..."
Our bugzilla database started giving this error during last week sometime. "Got error 127 from table handle". I Googled it, and came to believe that "repairing" and "optimizing" the table should sort out my problem, only to be shocked to see that over 10 000 records have been deleted by the repair/optimise. You see, this is not an option. We have over 18 000 bugs logged on our system, and as an organising our size, we need to comply to certain SAS70 requirements. Losing 10 000 records on our bugs database will fail the entire organisation the SAS70 reward, and guess what... it's on my plate, and if I can't do anything about it... people will talk bad about me for long after I've left the company.

I understand that the table records has gone corrupt. How it went corrupt I don't know and why it was working fine with over 10 000 corrputed records for the last 2 years, I also don't know. But right now it's not my job to understand it... I need to fix it, and keep every record in tact.

I've done a restore of the data all the way back to the day just before it crashed. When I ran a repair and optimize then, it did the same thing... over 10 000 records dissapear. PLEASE HELP. I am despirate!

Best 4 Students From Each State (was "help With Select Statement In SQL")
I've got a database that contains names of registered students with the states they come from. I intend to select 4 each from every state that has the highest total scores. I use PHP and MYSQL database.

NAME STATE TOTAL Course
Simon Alabama 56 Computer Science
Mark Alabama 85 Electrical Engineering
John Washington 45 Computer Science
Linda Florida 99 Statistics
Fred Florida 23 Mehcanical Engineering

This is just an illustration of how the database looks like.

the sql statement should select the best 4 students from each state based on thier total scores.

"Unable To Select Requested Database."
i currenty run a game. Well just adding flies now and sorting it out etc..... but when i go to like online.php or anyother flie that the DB runs off.. i get "Unable to select requested database."

Select Where Four Of The Ten Fields Are Same (was "query")
I have a table with ten fields. Now I want to select * from table where four of the ten fields are same. How can I do the query?

MySQL "SELECT" Speed
I've read from MySQL's page about optimization, but still have two specific questions:

1) Let's say I do something like "SELECT * FROM table WHERE col1=val1". And, in this specific case, I know that any time col1=val1, that col2 will always equal val2. So, would it be any faster (or slower) to do: "SELECT * FROM table WHERE col1=val1 AND col2=val2"?

2) Does the order of the argument in the WHERE part affect speed? Ex: "WHERE col_index=val1 AND col=val2" versus "WHERE col=val2 AND col_index=val1"?

"select Into Outfile " Issue
I am running MYSQL 5.0 ON WINXP pro.

I have the following procedure:

Select From Table Where Fieldvalue != ""
Does anyone know the MySQL Query for selecting all fields from a table where the fieldvalues do NOT equal nothing?

SELECT Statement Using WHERE That Involves Value From "next" Row?
Is is possible to construct a SELECT statement that contains a WHERE
clause that uses the value from a column in the "next" row?

ie. given a table with a single field named "myField" with the
following values I want a SELECT statement that selects the rows
"WHERE myField='1' and [NEXT ROW]myField = '2' ":

5
6
1
2
1
3

Select Value Separated By Comma &quot;,&quot;
how to select the value which separated by ',' or comma?

SELECT Statement Using WHERE That Involves Value From "next" Row?
Is is possible to construct a SELECT statement that contains a WHERE
clause that uses the value from a column in the "next" row?

ie. given a table with a single field named "myField" with the
following values I want a SELECT statement that selects the rows
"WHERE myField='1' and [NEXT ROW]myField = '2' ":

5
6
1
2
1
3

Algorithm Of "select" Statement
As I have to access MySQL database in Pocket PC, I'm developing a
evc++ program to read and retrieve data from MySQL table.

Where can I get some detail information about how "select" and "where"
statements work in the format, index and data files of MySQL database?

Impossible "select Statement"
I have a table with 3 simple fields all 2 varchar 1 double.

distributor,manufactutrerssku,cost

I have several diffent distributors listed in my table and some of them carry the same manufacturers products so I am trying to find out which skus are available at more than one distributor and where the cost is best. This is simple enought to do in php but on a select line I am lost. Can this be done or is it impossible?

Select &quot;german, French&quot; Only With &quot;german&quot;
in a table I have this entry in the column "language":

"GERMAN, FRENCH"

how do i have to make/modify my mysql-syntax so that i can select the entry abowe only with the word: "GERMAN"? Is this possible or do i have to make a data manipulation first?

"Select Least" Condition?
I have a MySQL table that has a float field...(apr)
What I am trying to do, is select the three rows that contain the least amount in the apr field, but am not too sure on what query/condition to use...

Could somebody please point me in the right direction?

Could I use something like:


SELECT * FROM table_name ORDER BY apr ASC LIMIT 3
D

How To Select &quot;Next&quot; Record
I've written an application around a database with about 15K records. I need to analyze 1 record at a time, but then skip to the next record based on the index order. Currently, I do this with the following statement:

SELECT * FROM Database ORDER BY IndexVariable1, IndexVariable2 LIMIT 25 ,1

This gets the 25th row of the database. When I want to get the next row, I change the 25 to 26 and repeat the same SELECT satement above.

The problem is that this is very slow. It takes about a half-second per select (unless the read was recently cached and is repeated).

I suspect tht I'm using a brute force method to read the next record, and that a quicker, more elegant method is possible.

Is there a "SELECT NEXT" statement that will execute more quickly than my ugly cludge? Or can anyone offer a better approach that I can try?

"select Match X Against Y" To %
I know this is impossible to do correct since relevance is not calculated as this in the first place, but is there some resonable convertion between the number you get when you
SELECT MATCH (<fulltext index>) AGAINST (<string>) AS relevance...
and percentage value?

Select &quot;MyValue&quot; FROM Tbl? (php)
I would like to do is have a certain value/variable returned in my search results. Like

$myValue="hello";

sql="SELECT column1,'".$myValue."' FROM myTable LIMIT 1"

so it would return something like

column1Info - hello


If you are wondering why I would need to do something like this, I'm trying to use a select in an insert statement to update two columns of a table, however one of the values inserted is a variable. I can do this:

INSERT INTO EB_books (catagoryID,bookName) select catagoryID,CURDATE() from EB_catagories LIMIT 1

But instead of the CURDATE() I would like that to be a value/varialbe in there.

Speed Up "SELECT *"
I'm really at a loss here, so i hope someone can help me.

I'm writing an application in VB and i want to search through a database on the server.
I have a table called TEST_TABLE, it has three fields:

id, name, log

"id" is a BIGINT and the primary key
"name" is a VARCHAR(128)
"log" is a MEDIUMTEXT

The table has 5000 entries.

When i perform a "SELECT * FROM TEST_TABLE" it takes almost 10 seconds to complete.

Is there any way to speed this up?

I already tried creating an index, but it doesn't seem to be possible to create an index that holds all the fields.

SELECT COUNT(*) Or SELECT .. LIMIT 1?
If the purpose of a query is to see if atleast 1 record exists which would be faster?

SELECT COUNT(*) or SELECT .. LIMIT 1?

Both would use a WHERE clause.

Select User's Templates Or Default Templates (was "How To Do This?")
I don't know if this is possible.

I have an email_template table, with id, user_id, template_id, subject, message.

There are default templates, marked with user_id = NULL. If a user customizes a template, that is copied with user_id = whatever their ID is.

So say there are 3 templates. Say user 1 has customized template 2. Then when the script lists the templates, it'll list template 1, the default, their customization of template 2, and the default template 3.

How can I do this? Basically, select all templates with user_id = null, unless there's one with user_id = whatever the user's id is, then select that one.

I had it working with some group by clause but I'm not sure why it worked. It might have been unintentional. but the query was

select * from email_template where user_id = 1 or user_id is null group by template_id order by template_id;
It always returned the template with a user id if it existed, but I don't know why.

"AS" In A Select
Probably not understand this fully but for some reason when I do the following query below:

SELECT u.uid, u.username, u.password, m.uid AS moderator_uid, a.uid AS admin_uid FROM vid_users u, vid_moderators m, vid_admins a WHERE u.uid= &#3910;' LIMIT 1

When I get the results, moderator_uid and admin_uid always is 1. Basically I want the query to look into 3 tables and all of them have a field called uid. I used the AS so it would look clearer on which uid I get. WHen the uid=4 moderator_uid and admin_uid is suppose to equal 4 also but why does it keep coming out as 1?

Select From Where Id=&quot;%&quot;??
I am having the user select radio buttons for criteria, and I want the query to search the database based on the criteria.

suppose in a table there is a field called favorite_number, and I have a form where the user picks a number, and I want to return all table entries that have that number as a favorite i.e.

select from members where favorite_number='number'

where number is set with POST.

Now... If I want to have another option 'all' so the user can select number one through 9, or 'all' with which he can return all table entries regardless of the favorite number. How do I do this?

I know I can do this with an if/then - i.e. if number='all' then.. else.. but I am attempting a complex filter with four or five criteria and figure there must be an easier way.

What I thought I might be able to do was if the user selected all, set number to % and do a query with-where number="%", but it didn't work.

"LIKE" In SQL Select
I need to get all results based on part of a string, eg:

"answer_2_0" or "answer_2_1"

so this is the SQL I made

SELECT blah,blah FROM table WHERE somehting=1 AND answer LIKE 'answer_2_%'

the problem is, I have results such as

answer_21_0
answer_22_1 etc

and they are returned.... I thought using the % AFTER the last "_" would work.

Searching For Numbers - &quot;close To&quot; Or &quot;approximate&quot;
I would like to know how to search a table for records where a particular field is "close to" a particular number.

For instance, let's say I have a table containing students and their most recent test scores. I'd like to see students who scored 7/10. That's easy enough (select * from table where score = 7). I'd also like to run another query to identify other students whose scores are not 7 but "close to" 7. Ie students who scored 6 or 8.

As an added bonus, I'd like to be able to do a related search that shows students who scored 7, then shows the other students ordered by how "close" they are to 7. Ie students who scored 6 or 8 are "closest" matches, and students who scored 1 are "furthest". I hope this makes sense!

Is there any pre-existing MySQL command that will do this? Or will I have to run separate queries for each value?

REQ: MySQL 4.0 Equivilent Of "DateDiff("m", Date, Now())=1"
I have a query that works in the rest of the SQL world

"SELECT invoice.*, invoice.Date
FROM invoice
WHERE (DateDiff("m", Date, Now())=1);"

which will give me all of last month's invoices.

However it doesn't work with MySQL 4.0.

While

"SELECT
Invoice.*
FROM
invoice
WHERE
(Month(Invoice.Date) = ((Month(Now()))-1))"

Is a close substituent, it will blowup in January.

Anyone have an equivalent expression for MySQL 4.0?

How To Select Count(*) And Something Else?
How do you select a count and another field without having to do two queries?

here's the query I'm using:-

SELECT
count(*) as totals, user

FROM user_posts
WHERE post='$md5'

SELECT COUNT
I'm counting rows from a mysql database able and trying to display the count. I have the following.

$count = "SELECT COUNT(*) AS newcount FROM stores";
$cr = mysql_query($count);
if (!$cr)
die(mysql_error());
if($cr){
//Make site ID now ...
$var1 = $newcount;
$var2 = P00;
$var3 = $var2.$var1;
}

The problem I have is thet $newcount seems to be empty. I have used count and not put "AS newcount" in the query but that made no difference. I have tried to echo the $newcount but again it is empty. Now, in PHP is there something else I must do to return the value of $newcount that I have missed?

SELECT Count
how to use SELECT Count.

Select *, Count
I want to perform a select query, but it doesnt return the data i have in mind. The result should be all info in 1 row with the highest date plus a total of game_id
This is what works best sofar.

SELECT * , COUNT( game_id )
FROM `battle`
WHERE game_id =4
GROUP BY game_id
ORDER BY b_date DESC
LIMIT 1

Yet this doesnt return the last date but the first. Everything else i tried the count function returned 1 even though it should be 20 for example.
How can i solve this?

SELECT COUNT(*)
I heard SELECT COUNT(*) can take a lot of resources if your counting a table with lots and lots of rows (hundred thousands, millions).
What if you add A WHERE clause to it? So something like:
SELECT COUNT(*) FROM table WHERE pid = ?
(pid is a index too btw)
IF adding a where clause, does it still scan the entire million plus rows, or only scans what is returned from the WHERE clause?



SELECT COUNT Or SUM()
Is there a difference between these two functions when your trying to gather how much a item appears in a database?
For example, which one will be better for a database w/ ~150,000 rows.

SELECT COUNT(category_id) FROM Threads WHERE category_id = '2'

Will return ~50,000 rows matching category 2

OR

SELECT SUM(category_id = '2') AS total FROM Threads
total will be ~50,000 rows also.

Select Count
I need to do the follow SQL..PHP Code:

 SELECT COUNT(t.id), COUNT(p.id) FROM threads t, posts p 

and add the two counts together... within the SQL query can i do this?
or do i just have to return the arrays and added the results seperatly.

Select Count Where Entries Are < 4
I want to count how many users have 4 or less entries in the table, so, so far i have
SQL
SELECT COUNT (*) AS fourLOCS FROM
(SELECT DISTINCT locsLog.locStudentID FROM locsLog)
which counts all the entries in the locsLog table and groups them by studentID so tells me how many users have made entries.
How do I limit this so it only gives me a total number of users who have made 4 or less entries. I think I'd need WHERE after the nested SELECT statement, but I don't know what I'd put in it. I tried
SQL
SELECT COUNT (*) AS fourLOCS FROM
(SELECT DISTINCT locsLog.locStudentID FROM locsLog)
WHERE fourLOCS <= 4
but had an error message (I'm doing it with an Access database with ASP and the message was 'Too few parameters. Expected 1').


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