Each page in my system has multiple page_objects.
I need to return the last_changed records of my page_objects per page.
To decrease DB-impact, I have a SELECT ... IN query to return each last-edited page_object per page:
SELECT object, f_page_id, page_object_id, last_change
FROM page_objects
WHERE f_page_id IN (page_id1, page_id2, page_id3, etc...) GROUP BY f_page_id
ORDER BY last_change ASC;
Of course this does not work, because GROUP BY is applied before ORDER BY, so I changed the query:
SELECT object, f_page_id, page_object_id, max(UNIX_TIMESTAMP(last_change))
FROM page_objects
WHERE f_page_id IN (page_id1, page_id2, page_id3, etc...) GROUP BY f_page_id
But this still does not return the last-edited page_object per page_id.
What am I doing wrong?
Your query does not specify to get the record for the latest last_change. Merely that it gets the latest value of last_change. The other non aggregate values (ie, not the result of an aggregate function like MAX or MIN) that are not mentioned in the GROUP BY clause can come from any row for the grouped values.
As such you use a sub query to get the latest value for each page, and then join that back against your main table to get the matching rows
Something like this:-
SELECT page_objects.object,
page_objects.f_page_id,
page_objects.page_object_id,
page_objects.last_change
FROM page_objects
INNER JOIN
(
SELECT f_page_id, MAX(last_change) AS latest_last_change
FROM page_objects
GROUP BY f_page_id
) sub0
ON page_objects.f_page_id = sub0.f_page_id
AND page_objects.last_change = sub0.latest_last_change
WHERE page_objects.f_page_id IN (page_id1, page_id2, page_id3, etc...)
ORDER BY last_change DESC
Note that MySQL is quite unusual at allowing you to have non aggregate columns that are not mentioned in the GROUP BY clause (as it is against SQL standards, except under very particular circumstances). Most flavours of SQL will issue an error if you try this, and MySQL has a configuration parameter which will similar cause it to reject such queries.
Related
I keep getting the same error: But as far as I can tell it is included in the Query:
SELECT TOP 1 tblOutlets.OutletName, tblOutlets.Parish, Count([Query OOSActions].OODate) AS CountOfOODate1
FROM tblOutlets INNER JOIN [Query OOSActions] ON tblOutlets.OutletID = [Query OOSActions].OutletLookup
WHERE ((([Query OOSActions].OODate) Between [Forms]![Settings]![StartDate] And [Forms]![Settings]![EndDate]) AND (([Query OOSActions].Classification)="Biscuit"))
GROUP BY tblOutlets.OutletName, tblOutlets.Parish
HAVING (((tblOutlets.Parish)="St. Mary"))
ORDER BY Count([Query OOSActions].OODate) DESC;
UNION
SELECT TOP 1 tblOutlets.OutletName, tblOutlets.Parish, Count([Query OOSActions].OODate) AS CountOfOODate1
FROM tblOutlets INNER JOIN [Query OOSActions] ON tblOutlets.OutletID = [Query OOSActions].OutletLookup
WHERE ((([Query OOSActions].OODate) Between [Forms]![Settings]![StartDate] And [Forms]![Settings]![EndDate]) AND (([Query OOSActions].Classification)="Biscuit"))
GROUP BY tblOutlets.OutletName, tblOutlets.Parish
HAVING (((tblOutlets.Parish)="St. Catherine"))
ORDER BY Count([Query OOSActions].OODate) DESC;
I solved it by including ORDER BY only in the first query and then removing all ending semicolons. Thanks for that bit #Uueerdo
When using "TOP" and "ORDER BY" in the second SQL statement of a UNION query, I have experienced that it runs the TOP instruction first and then the "ORDER BY", so it makes no sense to order by anything here. With a simpler SQL example:
SELECT TOP 1 Ingresos.ID_Fra, Ingresos.Tipo, Ingresos.Numero, Ingresos.Fecha, "First Query" AS Tbl
FROM Ingresos
ORDER BY Ingresos.Fecha DESC
UNION
SELECT TOP 5 IngresosAnulados.ID_Fra, IngresosAnulados.Tipo, IngresosAnulados.Numero, IngresosAnulados.Fecha, "DEL" AS Tbl
FROM IngresosAnulados
ORDER BY Fecha DESC;
Source table: IngresosAnulados:
Assuming that the data in "IngresosAnulados" are these 10 records, the defined SQL statement shows the following result:
As you can see, it has taken five records from the second table and has ordered them by the field "Fecha", as specified, but we do not know what the criteria are for having selected the five records that it has chosen.
By the way, it is necessary to indicate the name of a field selected in the first query as the order of any of the union queries (except the first one). That's just what the error message says (The ORDER BY expression includes fields that are not selected by the query).
So you will need two independent queries (at least, an independent query for the second SQL statement) to get the record(s) that interests you in each of them and then join them in a UNION query if you really want the x top most of each UNION query to be displayed.
Ive got a simple query that is used on a search. My problem is with this query is that as the records in mysql are added everytime there is a transaction, the query returns a list of data when there could only be one or a few more rows instead of a lot more.
SQLFliddle
As you can see here - the query returns a lot of rows, where I want it to return
BLSH103 A001A 31 24/01/2014
Can the qty where the product name & pallet space are the same be summed? And then show the largest date?
just use a sum function on t.Quantity (and a group by clause)
SELECT (t.ProductName) as Pname ,(s.PalletSpace) as PSpace, sum(t.Quantity) as Qty,(t.TransactionDate) as Transac
FROM PalletSpaces s
JOIN ProductTrans t
ON s.PalletSpaceID = t.PalletSpace
WHERE t.ProductName LIKE 'BLSH103' OR s.PalletSpace LIKE 'BLSH103'
group by
Pname,
pSpace,
Transac -- if you want to group by date also...
By the way, using LIKE this way (without %) doesn't make much sense...
see SqlFiddle
You just need to use GROUP BY and SUM in this way:
SELECT (t.ProductName) as Pname ,(s.PalletSpace) as PSpace, SUM(t.Quantity) as Qty,(t.TransactionDate) as Transac
FROM PalletSpaces s
JOIN ProductTrans t
ON s.PalletSpaceID = t.PalletSpace
WHERE t.ProductName LIKE 'BLSH103' OR s.PalletSpace LIKE 'BLSH103'
GROUP BY t.ProductName, s.PalletSpace;
I have the following query:
SELECT routes.route_date, time_slots.name, time_slots.openings, time_slots.appointments
FROM routes
INNER JOIN time_slots ON routes.route_id = time_slots.route_id
WHERE route_date
BETWEEN 20140109
AND 20140115
AND time_slots.openings > time_slots.appointments
ORDER BY route_date, name
This works just fine and will produce the following results:
What I want to do is only return one name per date. So the 9th, name = 1, would only have 1 result, rather than 2, as it currently does.
UPDATE: See the SQLFIDDLE for different type of solutions here: http://sqlfiddle.com/#!2/9ac65b/6
Will it solve your request if you use...
SELECT DISTINCT routes.route_date...your query... ?
It depends if you know that your rows always will have the same values, for same date/name.
Otherwise use group by...
(which I think suits your request best)
SELECT routes.route_date, time_slots.name, sum(time_slots.openings), sum(time_slots.appointments)
FROM routes
INNER JOIN time_slots ON routes.route_id = time_slots.route_id
WHERE route_date
BETWEEN 20140109
AND 20140115
AND time_slots.openings > time_slots.appointments
group by routes.route_date, time_slots.name
ORDER BY route_date, name
(i did a sum for the openings and appointments, you could do min, max, count, etc. Pick the one that fits your requirements best!)
You need to figure out which "name" you want when there are several for the same date.
Then you can group by date and select the right "name" by using an aggregate function like COUNT, MAX, etc.
I can't help you more if you don't explain your rule for picking one.
select tblProductMaster.*,AVG(tblReviewMaster.Rating) from tblProductMaster
left join tblReviewMaster
on tblProductMaster.ProductID = tblReviewMaster.ProductID
Group By tblProductMaster.ProductID
This query is returning an error:
Column 'tblReviewMaster.ReviewID' is invalid in the select list because it is not contained in either an aggregate function or the
GROUP BY clause.
It is not allowing me to have any column with AVG function... if I write
select AVG(tblReviewMaster.Rating) from tblProductMaster ...
then it works fine
So what to do to get product details from tblProductMaster also?
Error message says "Column 'tblReviewMaster.ReviewID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
This means all the columns other than column in aggregate functions(AVG) should be a part of Group By Clause. So if * means (Column 1, Column 2....etc) so all of these columns must be present in GroupBy clause.
So your query would be
select tblProductMaster.*,AVG(tblReviewMaster.Rating) from tblProductMaster
left join tblReviewMaster
on tblProductMaster.ProductID = tblReviewMaster.ProductID
Group By tblProductMaster.*
By *, I mean write all columns that represent *. * won't work here.
Please find more details on MSDN
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?