$qb = $this->createQueryBuilder('t');
return $qb
->join('t.customers', 'c')
->where($qb->expr()->eq('t.user', $user->getId()))
->andWhere($qb->expr()->gt($qb->expr()->count('c'), 0))
->orderBy('t.name')->getQuery()->getResult();
The above query (Doctrine2 generated one) is giving me this error:
#1111 - Invalid use of group function
but the strange thing is i'm not using GROUP BY. Any help is much appreciated, thanks.
SELECT t0_.id AS id0,
t0_.slug AS slug1,
t0_.name AS name2,
t0_.description AS description3,
t0_.user_id AS user_id4
FROM tag t0_
INNER JOIN customers_tags c2_ ON t0_.id = c2_.tag_id
INNER JOIN customer c1_ ON c1_.id = c2_.customer_id
WHERE t0_.user_id = 1 AND COUNT(c1_.id) > 0
ORDER BY t0_.name ASC
You are using an aggregate function count() in the where clause which is not allowed.
Conditions on aggregate functions need to go into a HAVING clause
....
WHERE t0_.user_id = 1
HAVING count(c1_.id) > 0
And of course you'll need to use a GROUP BY to get correct results (although MySQL will probably let you get away with not using a GROUP BY - but then the results are unpredictable)
There is no need in joins and havings. Simply use SIZE function:
$qb->where('SIZE(t.customers) = 0');
This will give you all rows without attached customers
"Count" can not be used in where without group by, count is "group function"
Related
When I run the below SQL statement, it correctly shows me what I expect:
SELECT Users.idQuiz as ThisIDQuiz,Rounds.RoundNr as ThisRoundNr, Questions.QuestionNr as ThisQuestionNr, Answer as ThisAnswer, Questions.QuestionScore AS QuestionScoreMax,AnswerCorrect,
(SELECT COUNT(*) as "Aantal Ploegen met dit antwoord"
FROM `Answers`
JOIN Questions on Answers.idQuestion = Questions.idQuestion
JOIN Rounds on Questions.idRound = Rounds.idRound
JOIN Users on Users.idUser = Answers.idUser
where (Users.idQuiz = ThisIDQuiz AND Rounds.RoundNr = ThisRoundNr AND Questions.QuestionNr=ThisQuestionNr AND Answers.Answer = ThisAnswer )
GROUP BY Users.idQuiz,Rounds.RoundNr, Questions.QuestionNr,Answer
) as NrOfTeamsWithThisAnswer,
(SELECT COUNT(*)
FROM Users
WHERE ((Users.idQuiz = ThisIDQuiz) AND (Users.UserType = 0))
) As TotalNrOfTeams,
AnswerCorrect *((Select TotalNrOfTeams)- (SELECT NrOfTeamsWithThisAnswer))as ScoreForThisAnswer
FROM `Answers`
JOIN Questions on Answers.idQuestion = Questions.idQuestion
JOIN Rounds on Questions.idRound = Rounds.idRound
JOIN Users on Users.idUser = Answers.idUser
WHERE Questions.QuestionType = 5
GROUP BY ThisAnswer
ORDER BY ThisIDQuiz, ThisRoundNr, ThisQuestionNr, ThisAnswer;
See Results of the query for what the result looks like.
I then create a VIEW from this statement. The view is created fine, but when I open it, I get the error "#1242 - Subquery returns more than 1 row".
I tried dropping and recreating the view, same result.
When I use the exact same SQL statement but without the penultimate line (GROUP BY ThisAnswer), it works fine (i.e. I can create the view and it opens without an error). This second view suits my purposes fine, so I can continue, but just out of curiosity: can someone explain this behaviour?
I use phpMyAdmin version 5.1.3 to do my SQL manipulations.
As #NickW asks, the statement GROUP BY ThisAnswer expects you to have an aggregate function (i.e. count, avg, max, min, etc.) somewhere in that main SELECT. Having a GROUP BY without an aggregate function will create errors. Either add the aggregate function, or remove the GROUP BY statement in the main (outermost) SELECT.
I have the following query:
SELECT OBJ_DESC_ERRORS.description, OBJ_DESC_ERRORS.object, OBJ_DESC_ERRORS.count_errors, OBJ_ERRORS.count_total FROM
(SELECT `metrics_event`.`description`, `metrics_event`.`object`, COUNT(`metrics_event`.`id`) AS `count_errors` FROM `metrics_event`
INNER JOIN `metrics_session` ON (`metrics_event`.`session_id` = `metrics_session`.`id`)
WHERE (`metrics_session`.`training_id` = 4 AND NOT (`metrics_session`.`completed_at` IS NULL) )
GROUP BY `metrics_event`.`description`, `metrics_event`.`object` ORDER BY `count_errors` DESC ) as OBJ_DESC_ERRORS
JOIN
(SELECT `metrics_event`.`object`, COUNT(`metrics_event`.`id`) AS `count_total` FROM `metrics_event`
INNER JOIN `metrics_session` ON (`metrics_event`.`session_id` = `metrics_session`.`id`)
WHERE (`metrics_session`.`training_id` = 4 AND NOT (`metrics_session`.`completed_at` IS NULL) )
GROUP BY `metrics_event`.`object` ORDER BY `count_total` DESC ) as OBJ_ERRORS
ON OBJ_DESC_ERRORS.object = OBJ_ERRORS.object
which produces the following result:
As you can see I'm basically running the same query twice. The reason for that is that I need to have that count_errors broken down by each aggregation of object + description, but I also need the count_total to be only aggregated by object. This was the way I could think of. Now I'd like to know if this is the best I can do or if it can be optimized even further.
If so I have no clue how. Googling and searching similar topics on this is difficult because the optimization task depends on the query itself, so keywords here didn't help me much.
Get rid of the inner ORDER BYs; they do nothing useful.
Rewrite the query something like this:
SELECT
me.description,
me.object,
SUM(...) AS count_errors,
SUM(...) AS count_total
FROM `metrics_event` AS me
INNER JOIN `metrics_session` AS ms ON (me.`session_id` = ms.`id`)
WHERE ms.`training_id` = 4
ms.`completed_at` IS NOT NULL
GROUP BY me.`description`, me.`object`
ORDER BY `count_total` DESC
Since a boolean expression evaluates as 1 for TRUE, else 0, devise the argument to SUM() to be a boolean expression that provides the desired COUNT.
I want to add a WHERE clause to my statement, but the problem is,
when I add the WHERE clause, I get an error "Invalid use of group function".
I also tried to replace the WHERE clause and write the condition into the
JOIN .. ON part, but the error is still there.
I want to add the condition so that only the rows " SUM(res.ReservationID) = 2" are returned.
-- works but we only want to get the rows in which the SUM = 2
SELECT ctr.ID, ctr.LastName, ctr.FirstName, SUM(res.ReservationID) as ReservierteSitze
FROM customer as ctr
INNER JOIN reservation AS res ON ctr.ID = res.CustomerID
Group by ctr.ID;
SELECT ctr.ID, ctr.LastName, ctr.FirstName, SUM(res.ReservationID) as ReservierteSitze
FROM customer as ctr
INNER JOIN reservation AS res ON ctr.ID = res.CustomerID
Group by ctr.ID
HAVING ReservierteSitze = 2;
The HAVING clause is like a where clause for the GROUP BY (applies to the groupings)
You can still have a WHERE clause before the GROUP BY clause, but that only applies to the individual rows before the grouping.
having(Aggregation function condition processing)
I have used the following query:
select tblclass.classname,tblattendance.id
from tblclass,tblattendance
where tblclass.classcode=tblattendance.classcode
and tblattendance.attdate='2013-07-01'
Output of this query is as follows:
Now what I want is rather than the above result I want count of different classes like IB-2,IC-5.
Please tell me what modifications do I need to made in my query to get the desired result
Use the Group By SQL clause and add the aggregate function Count
select tblclass.classname, Count(tblattendance.id) as counter
from tblclass,tblattendance
where tblclass.classcode=tblattendance.classcode and tblattendance.attdate='2013-07-01'
group by tblclass.classname
Try this
select count(tblattendance.id),tblclass.classname from tblclass,tblattendance
where tblclass.classcode=tblattendance.classcode and tblattendance.attdate='2013-07-01'
group by tblclass.classname
Use COUNT() function for that with GROUP BY. Also use JOIN.
SELECT tc.classname, COUNT(tc.classname) AS COUNTS
FROM tblclass tc
JOIN tblattendance tt
ON tc.classcode = tt.classcode
WHERE tt.attdate='2013-07-01'
GROUP BY tc.classname
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?