MySQL COUNT() causing empty array() return - mysql

MySQL Server Version: Server version: 4.1.14
MySQL client version: 3.23.49
Tables under discussion: ads_list and ads_cate.
Table Relationship: ads_cate has many ads_list.
Keyed by: ads_cate.id = ads_list.Category.
I am not sure what is going on here, but I am trying to use COUNT() in a simple agreggate query, and I get blank output.
Here is a simple example, this returns expected results:
$queryCats = "SELECT id, cateName FROM ads_cate ORDER BY cateName";
But if I modify it to add the COUNT() and the other query data I get no array return w/ print_r() (no results)?
$queryCats = "SELECT ads_cate.cateName, ads_list.COUNT(ads_cate.id),
FROM ads_cate INNER JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName ORDER BY cateName";
Ultimately, I am trying to get a count of ad_list items in each category.
Is there a MySQL version conflict on what I am trying to do here?
NOTE: I spent some time breaking this down, item by item and the COUNT() seems to cause the array() to disappear. And the the JOIN seemed to do the same thing... It does not help I am developing this on a Yahoo server with no access to the php or mysql error settings.

I think your COUNT syntax is wrong. It should be:
COUNT(ads_cate.id)
or
COUNT(ads_list.id)
depending on what you are counting.

Count is an aggregate. means ever return result set at least one
here you be try count ads_list.id not null but that wrong. how say Myke Count(ads_cate.id) or Count(ads_list.id) is better approach
you have inner join ads_cate.id = ads_list.category so Count(ads_cate.id) or COUNT(ads_list.id) is not necessary just count(*)
now if you dont want null add having
only match
SELECT ads_cate.cateName, COUNT(*),
FROM ads_cate INNER JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName
having not count(*) is null
ORDER BY cateName
all
SELECT ads_cate.cateName, IFNULL(COUNT(*),0),
FROM ads_cate LEFT JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName
ORDER BY cateName

Did you try:
$queryCats = "SELECT ads_cate.cateName, COUNT(ads_cate.id)
FROM ads_cate
JOIN ads_list ON ads_cate.id = ads_list.category
GROUP BY ads_cate.cateName";
I am guessing that you need the category to be in the list, in that case the query here should work. Try it without the ORDER BY first.

You were probably getting errors. Check your server logs.
Also, see what happens when you try this:
SELECT COUNT(*), category
FROM ads_list
GROUP BY category

Your array is empty or disappear because your query has errors:
there should be no comma before the FROM
the "ads_list." prefix before COUNT is incorrect
Please try running that query directly in MySQL and you'll see the errors. Or try echoing the output using mysql_error().
Now, some other points related to your query:
there is no need to do ORDER BY because GROUP BY by default sorts on the grouped column
you are doing a count on the wrong column that will always give you 1
Perhaps you are trying to retrieve the count of ads_list per ads_cate? This might be your query then:
SELECT `ads_cate`.`cateName`, COUNT(`ads_list`.`category`) `cnt_ads_list`
FROM `ads_cate`
INNER JOIN `ads_list` ON `ads_cate`.`id` = `ads_list`.`category`
GROUP BY `cateName`;
Hope it helps?

Related

MySQL DISTINCT returning not so distinct results

Good day,
I have a small issue with MySQL Distinct.
Trying the following query in my system :
SELECT DISTINCT `booking_id`, `booking_ticket`, `booking_price`, `bookingcomment_id`, `bookingcomment_message` FROM `mysystem_booking`
LEFT JOIN `mysystem_bookingcomment` ON `mysystem_booking`.`booking_id` = `mysystem_bookingcomment`.`bookingcomment_link`
WHERE `booking_id` = 29791
The point is that there are bookings like 29791 that have many comments added.
Let's say 10. Then when running the above query I see 10 results instead of one.
And that's not the way DISTINCT supposes to work.
I simply want to know if there are any comments. If the comment ID is not 0 then there is a comment. Of course I can add COUNT(blabla) as comment_number but that's a whole different story. For me now I'd like just to have this syntax right.
You may try aggregating here, to find which bookings have at least a single comment associated with them:
SELECT
b.booking_id,
b.booking_ticket,
b.booking_price
FROM mysystem_booking b
LEFT JOIN mysystem_bookingcomment bc
ON b.booking_id = bc.bookingcomment_link
WHERE
b.booking_id = 29791
GROUP BY
b.booking_id
HAVING
COUNT(bc.bookingcomment_link) > 0;
Note that depending on your MySQL server mode, you might have to also add the booking_ticket and booking_price columns to the GROUP BY clause to get the above query to run.
You can try below - using a case when expression
SELECT DISTINCT `booking_id`, `booking_ticket`, `booking_price`, `bookingcomment_id`,
case when `bookingcomment_message`<>'0' then 'No' else 'Yes' end as comments
FROM `mysystem_booking`
LEFT JOIN `mysystem_bookingcomment` ON `mysystem_booking`.`booking_id` = `mysystem_bookingcomment`.`bookingcomment_link`
WHERE `booking_id` = 29791

SQL JOIN gives double results

My database and SQL:
http://sqlfiddle.com/#!9/ebddb/1/0
Problem:
It's returning duplicates, with the wrong data in the name-column, when there are less than 7 records in the notchtype-table
My Question:
Why does it return duplicates and how to prevent it?
Expected result:
This fiddle shows the expected result: http://sqlfiddle.com/#!9/22660/1
In this result the only thing more added than in my actual database and SQL are 2 records in the notchtype-table
So the id, notchid and number columns should be unique in the returned rows.
The screenshot in the answer of Piyush Gupta is showing the right expected result. The same query on SQL fiddle and locally on MariaDB version 10.1.9 are returning something different
Notes:
I found out that when there at least 7 records in the notchtype table, there are suddenly no duplicates anymore and the problem is 'solved'.
The null values should indeed be null.
The size-column is actually returning the right values, although the LEFT JOIN is more or less the same
The ID's in notches.notchdescr 'connects' with the ID's in notchtype.notchtypeid column and is returned as the name column in the fiddle
The ID's in notches.notchsize 'connects' with the ID's in notchsize.notchsizeid column and is returned as the size column in the fiddle
Not working:
INNER JOIN, don't know why
DISTINCT, because the name-columns have different values, so there not exact duplicates
GROUP BY, because it returns all the same values in the name-column
Update on answer/comments from Piyush Gupta
Query executed on MySQL 5.7:
SELECT
notches.id,
notches.notchid,
notches.number,
notches.xcoord,
notches.ycoord,
notches.mapid,
notches.location,
notches.date,
notches.price,
notches.invoiced,
notchsize.size AS notchsize,
notchtype.name AS notchdescr
FROM
notches
LEFT JOIN
notchtype ON
notches.notchdescr = notchtype.notchtypeid
LEFT JOIN
notchsize ON
notches.notchsize = notchsize.notchsizeid
WHERE
notches.del = 0
AND
notches.projectid = '2016032411364363055'
GROUP BY notches.id, notches.notchid, notches.number
ORDER BY notches.number ASC
Result:
SOLVED!
LEFT JOIN on VARCHAR = BIGINT field causes the strange returned values. See answer and comments of Piyush Gupta
You missed the GROUP BY in your query for Aggregate the data. so your query will be,
SELECT
notches.id,
notches.notchid,
notches.number,
notches.xcoord,
notches.ycoord,
notches.mapid,
notches.location,
notches.descr,
notches.date,
notches.price,
notches.invoiced,
notchtype.name AS notchdescr,
notchsize.size AS notchsize
FROM
notches
LEFT JOIN
notchtype ON
notches.notchdescr = notchtype.notchtypeid
LEFT JOIN
notchsize ON
notches.notchsize = notchsize.notchsizeid
WHERE
notches.del = 0
AND
notches.projectid = '2016032411364363055'
GROUP BY notches.id,
notches.notchid,
notches.number
ORDER BY notches.number ASC;
Output: ONLINE DEMO HERE
NOTE: I Imported your data structure locally and I'm getting same output which is your expectation but In SQLFiddle, notchtype.name AS notchdescr column is not executing in SQLFiddle that is showing only name column of notchtype table. So you can use above query and check locally in your database. I hope you will get require output.
Screenshot(Using MySQL Workbench)
Update 1: It was strange error. I reviewed database structure and found solution that was data type issue only. You were joining bigint and varchar data type so you need to correct data type. Here I'm changing data type bigint to varchar for notchsizeid in notchsize table and notchtypeid in notchtype table. Finally your Expected output is coming. You can SEE OUTPUT HERE.
You can do by using group by . But you need to tell your logic for this.
SELECT
notches.id,
notches.notchid,
notches.number,
notches.xcoord,
notches.ycoord,
notches.mapid,
notches.location,
notches.descr,
notches.date,
notches.price,
notches.invoiced,
notchtype.name AS notchdescr,
notchsize.size AS notchsize
FROM
notches
LEFT JOIN
notchtype ON
notches.notchdescr = notchtype.notchtypeid
LEFT JOIN
notchsize ON
notches.notchsize = notchsize.notchsizeid
WHERE
notches.del = 0
AND
notches.projectid = '2016032411364363055'
group by id
ORDER BY notches.number ASC

MySQL: Subquery returns more than 1 row

I know this has been asked plenty times before, but I cant find an answer that is close to mine.
I have the following query:
SELECT c.cases_ID, c.cases_status, c.cases_title, ci.custinfo_FName, ci.custinfo_LName, c.cases_timestamp, o.organisation_name
FROM db_cases c, db_custinfo ci, db_organisation o
WHERE c.userInfo_ID = ci.userinfo_ID AND c.cases_status = '2'
AND organisation_name = (
SELECT organisation_name
FROM db_sites s, db_cases c
WHERE organisation_ID = '111'
)
AND s.sites_site_ID = c.sites_site_ID)
What I am trying to do is is get the cases, where the sites_site_ID which is defined in the cases, also appears in the db_sites sites table alongside its organisation_ID which I want to filter by as defined by "organisation_ID = '111'" but I am getting the response from MySQL as stated in the question.
I hope this makes sense, and I would appreciate any help on this one.
Thanks.
As the error states your subquery returns more then one row which it cannot do in this situation. If this is not expect results you really should investigate why this occurs. But if you know this will happen and want only the first result use LIMIT 1 to limit the results to one row.
SELECT organisation_name
FROM db_sites s, db_cases c
WHERE organisation_ID = '111'
LIMIT 1
Well the problem is, obviously, that your subquery returns more than one row which is invalid when using it as a scalar subquery such as with the = operator in the WHERE clause.
Instead you could do an inner join on the subquery which would filter your results to only rows that matched the ON clause. This will get you all rows that match, even if there is more than one returned in the subquery.
UPDATE:
You're likely getting more than one row from your subquery because you're doing a cross join on the db_sites and db_cases table. You're using the old-style join syntax and then not qualifying any predicate to join the tables on in the WHERE clause. Using this old style of joining tables is not recommended for this very reason. It would be better if you explicitly stated what kind of join it was and how the tables should be joined.
Good pages on joins:
http://dev.mysql.com/doc/refman/5.0/en/join.html (for the right syntax)
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html (for the differences between the types of joins)
I was battling this for an hour, and overcomplicated it completely. Sometimes a quick break and writing it out on an online forum can solve it for you ;)
Here is the query as it should be.
SELECT c.cases_ID, c.cases_status, c.cases_title, ci.custinfo_FName, ci.custinfo_LName, c.cases_timestamp, c.sites_site_ID
FROM db_cases c, db_custinfo ci, db_sites s
WHERE c.userInfo_ID = ci.userinfo_ID AND c.cases_status = '2' AND (s.organisation_ID = '111' AND s.sites_site_ID = c.sites_site_ID)
Let me re-write what you have post:
SELECT
c.cases_ID, c.cases_status, c.cases_title, ci.custinfo_FName, ci.custinfo_LName,
c.cases_timestamp, c.sites_site_ID
FROM
db_cases c
JOIN
db_custinfo ci ON c.userInfo_ID = ci.userinfo_ID and c.cases_status = '2'
JOIN
db_sites s ON s.sites_site_ID = c.sites_site_ID and s.organization_ID = 111

why wont multiple where clause work

I have 2 paramters ( $memberparamter and $rest_id), that i am getting from the user. But every time my server runs the statement, it does not find anything. I have double checked with my database, and it says the desired output, does exist. If i delete one of the where clause, it works great.
Have i done it the wrong way?
This is my sql statement:
SELECT
eso.order_id as order_id,
eso.member_id as member_id,
esoi.title as title,
dl.used_date as checked,
dl.order_item_id as order_item_id
FROM exp_store_orders as eso
inner join exp_store_order_items as esoi on (eso.order_id = esoi.order_id)
inner join exp_deal_keys as dl on dl.order_item_id = esoi.order_item_id
where eso.member_id = '$memberparamter' and esoi.entry_id = '$rest_id'
and eso.order_paid > 0
group BY eso.transaction_id
ORDER BY eso.transaction_id desc
You need to specify which where clause fixes the problem. If I were to speculate, I would guess that you misspelled '$memberparamter' and it really should be '$memberparameter' -- on the belief that you would spell "parameter" correctly in your code.
Is it the GROUP BY that is causing the problem. Why do you have GROUP BY when you are not aggregating any of your SELECT columns?

count(*) in mysql returning only one record

I want to count how many records from another table in the same select statement , i used Left join
and in the select statement i put count(ag.*)
see the
Example :
$q = Doctrine_Query::create()
->select("a.answer_id,a.date_added , count(ag.content_id) AS agree_count")
->from('Answer a')
->leftJoin("a.Agree ag ON a.answer_id = ag.content_id AND ag.content_type = 'answer' ")
->where('a.question_id= ? ', $questionId)
But its only returning the first record, can i Fix that? or to make another table and make it only for counting ?
You are missing a GROUP BY in your query.
More infos here.
When you don't have a GROUP BY clause, it's normal to get only one row.
Count(*) will only return one record if you don't use Group By. You are asking it to count all the records, so there can be only one result.
The count() SQL function changes how results are returned from the database - without a GROUP BY the database will only return one record, regardless of other colums in the SELECT.
if you add:
group by a.answer_id
to the end of your SQL query, that might DWYM.