There are alot questions on this topic, still can't figure out a way to make this work.
The query I'm doing is:
SELECT `b`.`ads_id` AS `ads_id`,
`b`.`bod_bedrag` AS `bod_bedrag`,
`a`. `ads_naam` AS `ads_naam`,
`a`.`ads_url` AS `ads_url`,
`a`.`ads_prijs` AS `ads_price`,
`i`.`url` AS `img_url`,
`c`.`url` AS `cat_url`
FROM `ads_market_bids` AS `b`
INNER JOIN `ads_market` AS `a`
ON `b`.`ads_id` = `a`.`id`
INNER JOIN `ads_images` AS `i`
ON `b`.`ads_id` = `i`.`ads_id`
INNER JOIN `ads_categories` AS `c`
ON `a`.`cat_id` = `c`.`id`
WHERE `i`.`img_order` = '0'
AND `b`.`u_id` = '285'
GROUP BY `b`.`ads_id`
HAVING MAX(b.bod_bedrag)
ORDER BY `b`.`bod_bedrag` ASC
But, the problem I keep seeing is that I need b.bod_bedrag to be sorted before the GROUP BY is taking place or so. Don't know how to explain it exactly.
The bod_bedrag i'm getting now are the lowest of the bids in the table. I need the highest.
Tried like everything, even tought of not grouping by but using DISTINCT. This didn't work either. Tried order by max, everything I know or could find on the internet.
Image 1 is the situation without the group by. Order By works great (ofc).
Image 2 is with the group by. As you can see, the lowest bid is taken as bod_bedrag. I need the highest.
Judging by your output you want:
SELECT amb.ads_id,
MAX(amb.bod_bedrag) max_bod_bedrag,
am.ads_naam,
am.ads_url,
am.ads_prijs ads_price,
ai.url img_url,
ac.url cat_url
FROM ads_market_bids amb
JOIN ads_images ai
ON ai.ads_id = amb.ads_id
AND ai.img_order = 0
JOIN ads_market am
ON am.id = amb.ads_id
JOIN ads_categories ac
ON ac.id = am.cat_id
WHERE amb.u_id = 285
GROUP BY amb.ads_id,
am.ads_naam,
am.ads_url,
am.ads_prijs,
ai.url,
ac.url
ORDER BY max_bod_bedrag ASC
I have also removed all the unecessary backtickery and aliasing of columns to the same name.
Your HAVING was doing nothing as all the groups 'have' a MAX(amb.bod_rag).
select distinct `b`.`ads_id` as `ads_id`, max(`b`.`bod_bedrag`) as `bod_bedrag`,
`a`.`ads_naam` as `ads_naam`, `a`.`ads_url` as `ads_url`, `a`.`ads_prijs` as `ads_price`,
`i`.`url` as `img_url`, `c`.`url` as `cat_url`
from `ads_market_bids` as `b`
inner join `ads_market` as `a` on `b`.`ads_id` = `a`.`id`
inner join `ads_images` as `i` on `b`.`ads_id` = `i`.`ads_id`
inner join `ads_categories` as `c` on `a`.`cat_id` = `c`.`id`
where `i`.`img_order` = '0' and `b`.`u_id` = '285'
group by b.ads_id, a.ads_naam, a.ads_url, a.ads_prijs, i.url, c.url
One approach is to simulate row_number() (which MySQL does not have), but it allows for selection - by record - rather than by aggregates which may come from disparate source records. It works by adding to variables to each row (it does not increase the number of rows) Then, using an ordered subquery those variables are set to 1 for the highest b.bod_bedrag for each b.ads_id, all other rows perb.ads_id` get a higher RN value. At the end we filter where RN = 1 (which equates the the record containing the highest bid value)
SELECT *
FROM (
SELECT
#row_num :=IF(#prev_value=`b`.`ads_id`, #row_num + 1, 1) AS RN
,`b`.`ads_id` AS `ads_id`
,`b`.`bod_bedrag` AS `bod_bedrag`
,`a`.`ads_naam` AS `ads_naam`
,`a`.`ads_url` AS `ads_url`
,`a`.`ads_prijs` AS `ads_price`
,`i`.`url` AS `img_url`
,`c`.`url` AS `cat_url`
, #prev_value := `b`.`bod_bedrag`
FROM `ads_market_bids` AS `b`
INNER JOIN `ads_market` AS `a` ON `b`.`ads_id` = `a`.`id`
INNER JOIN `ads_images` AS `i` ON `b`.`ads_id` = `i`.`ads_id`
INNER JOIN `ads_categories` AS `c` ON `a`.`cat_id` = `c`.`id`
CROSS JOIN
( SELECT #row_num :=1
, #prev_value :=''
) vars
WHERE `i`.`img_order` = '0'
AND `b`.`u_id` = '285'
ORDER BY `b`.`ads_id`, b`.`bod_bedrag` DESC
)
WHERE RN = 1;
You can even turn off that silly GROUP BY extension, details in the man page:
MySQL Extensions to GROUP BY
Related
okay guys, this is a big one that’s confusing as hell.
I’m creating a forum type dealio: I have an array of Topics and each topic has an array of Posts associated with the Topic. The Topics list page should show the latest Post from that specific Topic. (Each topic is in a category as well)
Topic Latest post
Check out my page John Smith - 10:00 PM
MYSQL
select `ct`.*, `a`.`username`, `x`.* from `community-topics` as `ct`
inner join `community-categories` as `cc` on `cc`.`communityCategoryId` = `ct`.`refCategoryId`
inner join `authentication` as `a` on `a`.`userId` = `ct`.`refCreatedBy`
inner join (
select `a2`.`username` AS lastPostUsername, `cp`.`createdAt` AS lastPostCreatedAt,
`cp`.`body`, `cp`.`refTopicId` from `community-posts` as `cp`
inner join `authentication` as `a2` on `a2`.`userId` = `cp`.`refCreatedBy`
order by `cp`.`createdAt` desc limit 1
) as x on `x`.`refTopicId` = `ct`.`communityTopicId`
where `cc`.`name` = 'general' order by `ct`.`createdAt` desc
This query actually works how I need it to. The only issue is that a row won’t return if the subquery is empty. I still want to return all of the data outside of the subquery even if the subquery is null / false / empty. I've tried using IFNULL / ISNULL, but I don't think I'm using it right with the additional joins in the subquery.
if I have 2 topics, 1 topic with 5 posts, 1 topic with 0 posts, only the topic with 5 posts will show up and the topic with 0 posts won’t show up because the subquery returns empty.
If the row is empty, I’d like to return something to the front end user showing something like “Sorry, no recent posts” or something along those lines.
Any help would be amazing!
You want a left join if you want to keep rows even when there is no match:
select `ct`.*, `a`.`username`, `x`.*
from `community-topics` `ct` inner join
`community-categories` `cc`
on `cc`.`communityCategoryId` = `ct`.`refCategoryId` inner join
`authentication` `a`
on `a`.`userId` = `ct`.`refCreatedBy` left join
(select `a2`.`username` AS lastPostUsername, `cp`.`createdAt` AS lastPostCreatedAt,
`cp`.`body`, `cp`.`refTopicId`
from `community-posts` as `cp` left join
`authentication` as `a2`
on `a2`.`userId` = `cp`.`refCreatedBy`
order by `cp`.`createdAt` desc limit 1
) x
on `x`.`refTopicId` = `ct`.`communityTopicId`
where `cc`.`name` = 'general'
order by `ct`.`createdAt` desc;
I would also recommend that you remove all the backticks. They just make the query harder to write and to read.
EDIT:
If I understand your comment:
select `ct`.*, `a`.`username`, `x`.*
from `community-topics` `ct` inner join
`community-categories` `cc`
on `cc`.`communityCategoryId` = `ct`.`refCategoryId` inner join
`authentication` `a`
on `a`.`userId` = `ct`.`refCreatedBy` left join
(select `a2`.`username` AS lastPostUsername, `cp`.`createdAt` AS lastPostCreatedAt,
`cp`.`body`, `cp`.`refTopicId`,
row_number() over (partition by refTopicId order by cp.created_at desc) as seqnum
from `community-posts` as `cp` left join
`authentication` as `a2`
on `a2`.`userId` = `cp`.`refCreatedBy`
) x
on `x`.`refTopicId` = `ct`.`communityTopicId` and seqnum = 1
where `cc`.`name` = 'general'
order by `ct`.`createdAt` desc;
How can I merge these two left joins: http://sqlfiddle.com/#!9/1d2954/69/0
SELECT d.`id`, (adcount + bdcount)
FROM `docs` d
LEFT JOIN
(
SELECT da.`doc_id`, COUNT(da.`doc_id`) AS adcount FROM `docs_scod_a` da
INNER JOIN `scod_a` a ON a.`id` = da.`scod_a_id`
WHERE a.`ver_a` IN ('AA', 'AB')
GROUP BY da.`doc_id`
) ad ON ad.`doc_id` = d.`id`
LEFT JOIN
(
SELECT db.`doc_id`, COUNT(db.`doc_id`) AS bdcount FROM `docs_scod_b` db
INNER JOIN `scod_b` b ON b.`id` = db.`scod_b_id`
WHERE b.`ver_b` IN ('BA', 'BB')
GROUP BY db.`doc_id`
) bd ON bd.`doc_id` = d.`id`
to be a Single left join just to ease its use in my code, while making it no less slower?
Let me first emphasize that your method of doing the calculation is the better method. You have two separate dimensions and aggregating them separately is often the most efficient method for doing the calculation. It is also the most scalable method.
That said, your query should be equivalent to this version:
SELECT d.id,
count(distinct a.id),
count(distinct b.id)
FROM docs d left join
docs_scod_a da
ON da.doc_id = d.id LEFT JOIN
scod_a a
ON a.id = da.scod_a_id AND a.ver_a IN ('AA', 'AB') LEFT JOIN
docs_scod_b db
ON db.doc_id = d.id LEFT JOIN
scod_b b
ON b.id = db.scod_b_id AND b.ver_b IN ('BA', 'BB')
GROUP BY d.id
ORDER BY d.id;
This query is more expensive than it looks, because the COUNT(DISTINCT) incurs additional overhead compared to COUNT().
And here is the SQL Fiddle.
And, because LEFT JOIN can return NULL values, your query is more correctly written as:
SELECT d.`id`, COALESCE(adcount, 0) + COALESCE(bdcount, 0)
If you were having problems with the results, this small change might fix those problems.
Performance may be a big problem, depending on sizes of each table. It appears to be an "inflate-deflate" situation since it first "inflates" the number of rows via JOIN, then "deflates" via GROUP BY. The formulation below avoids inflation-deflation.
But first, if I understand this subquery correctly, this
SELECT da.`doc_id`, COUNT(da.`doc_id`) AS adcount
FROM `docs_scod_a` da
INNER JOIN `scod_a` a ON a.`id` = da.`scod_a_id`
WHERE a.`ver_a` IN ('AA', 'AB')
GROUP BY da.`doc_id`
can be rewritten as
SELECT `doc_id`,
( SELECT COUNT(*)
FROM `scod_a`
WHERE `id` = da.`scod_a_id`
AND `ver_a` IN ('AA', 'AB')
) AS adcount
FROM `docs_scod_a` AS da
If that is correct, then the entire query becomes
SELECT d.id,
( SELECT COUNT(*)
FROM docs_scod_a ds
JOIN scod_a s ON s.id = ds.scod_a_id
WHERE ds.doc_id = d.id
AND s.ver_a IN ('AA', 'AB')
) +
( SELECT COUNT(*)
FROM docs_scod_b ds
JOIN scod_b s ON s.id = ds.scod_b_id
WHERE ds.doc_id = d.id
AND s.ver_b IN ('BA', 'BB')
)
FROM docs AS d
Which needs these indexes:
docs_scod_a: (doc_id, scod_a_id), (scod_a_id, doc_id)
docs_scod_b: (doc_id, scod_b_id), (scod_b_id, doc_id)
scod_a: (ver_a, id)
scod_b: (ver_b, id)
docs: -- presumably has PRIMARY KEY(id)
Note the lack of GROUP BY.
docs_scod_a smells like a many-to-many mapping table. I recommend you follow the tips here.
(No COALESCE is needed since COUNT will simply return zero.)
(I don't know whether my version is better (faster or whatever) than Gordon's, nor whether my indexes will help his formulation.)
I have a very large table (~1 000 000 rows) and complicated query with unions, joins and where statements (user can select different ORDER BY columns and directions). I need to get a row count for pagination. If I run query without counting rows it completes very fast. How can I implement pagination in fastest way?
I tried to use EXPLAIN SELECT and SHOW TABLE STATUS to get approximate row count, but it is very different from real row count.
My query is like this one (simplyfied):
SELECT * FROM (
(
SELECT * FROM table_1
LEFT JOIN `table_a` ON table_1.record_id = table_a.id
LEFT JOIN `table_b` ON table_a.id = table_b.record_id
WHERE table_1.a > 10 AND table_a.b < 500 AND table_b.c = 1
ORDER BY x ASC
LIMIT 0, 10
)
UNION
(
SELECT * FROM table_2
LEFT JOIN `table_a` ON table_2.record_id = table_a.id
LEFT JOIN `table_b` ON table_a.id = table_b.record_id
WHERE table_2.d < 10 AND table_a.e > 500 AND table_b.f = 1
ORDER BY x ASC
LIMIT 0, 10
)
) tbl ORDER BY x ASC LIMIT 0, 10
Query result without limiting is about ~100 000 rows, how can I get this approximate count in fastest way?
My production query example is like this one:
SELECT SQL_CALC_FOUND_ROWS * FROM (
(
SELECT
articles_log.id AS log_id, articles_log.source_table,
articles_log.record_id AS id, articles_log.dat AS view_dat,
articles_log.lang AS view_lang, '1' AS view_count, '1' AS unique_view_count,
articles_log.user_agent, articles_log.ref, articles_log.ip,
articles_log.ses_id, articles_log.bot, articles_log.source_type, articles_log.link,
articles_log.user_country, articles_log.user_platform,
articles_log.user_os, articles_log.user_browser,
`contents`.dat AS source_dat, `contents_trans`.header, `contents_trans`.custom_text
FROM articles_log
INNER JOIN `contents` ON articles_log.record_id = `contents`.id
AND articles_log.source_table = 'contents'
INNER JOIN `contents_trans` ON `contents`.id = `contents_trans`.record_id
AND `contents_trans`.lang='lv'
WHERE articles_log.dat > 0
AND articles_log.dat >= 1488319200
AND articles_log.dat <= 1489355999
AND articles_log.bot = '0'
AND (articles_log.record_id NOT LIKE '%\_404' AND articles_log.record_id <> '404'
OR articles_log.source_table <> 'contents')
)
UNION
(
SELECT
articles_log.id AS log_id, articles_log.source_table,
articles_log.record_id AS id, articles_log.dat AS view_dat,
articles_log.lang AS view_lang, '1' AS view_count, '1' AS unique_view_count,
articles_log.user_agent, articles_log.ref, articles_log.ip,
articles_log.ses_id, articles_log.bot,
articles_log.source_type, articles_log.link,
articles_log.user_country, articles_log.user_platform,
articles_log.user_os, articles_log.user_browser,
`news`.dat AS source_dat, `news_trans`.header, `news_trans`.custom_text
FROM articles_log
INNER JOIN `news` ON articles_log.record_id = `news`.id
AND articles_log.source_table = 'news'
INNER JOIN `news_trans` ON `news`.id = `news_trans`.record_id
AND `news_trans`.lang='lv'
WHERE articles_log.dat > 0
AND articles_log.dat >= 1488319200
AND articles_log.dat <= 1489355999
AND articles_log.bot = '0'
AND (articles_log.record_id NOT LIKE '%\_404' AND articles_log.record_id <> '404'
OR articles_log.source_table <> 'contents')
)
) tbl ORDER BY view_dat ASC LIMIT 0, 10
Many thanks!
If you can use UNION ALL instead of UNION (which is a shortcut for UNION DISTINCT) - In other words - If you don't need to remove duplicates you can try to add the counts of the two subqueries:
SELECT
(
SELECT COUNT(*) FROM table_1
LEFT JOIN `table_a` ON table_1.record_id = table_a.id
LEFT JOIN `table_b` ON table_a.id = table_b.record_id
WHERE table_1.a > 10 AND table_a.b < 500 AND table_b.c = 1
)
+
(
SELECT COUNT(*) FROM table_2
LEFT JOIN `table_a` ON table_2.record_id = table_a.id
LEFT JOIN `table_b` ON table_a.id = table_b.record_id
WHERE table_2.d < 10 AND table_a.e > 500 AND table_b.f = 1
)
AS cnt
Without ORDER BY and without UNION the engine might not need to create a huge temp table.
Update
For your original query try the following:
Select only count(*).
Remove OR articles_log.source_table <> 'contents' from first part (contents) since we know it's never true.
Remove AND (articles_log.record_id NOT LIKE '%\_404' AND articles_log.record_id <> '404' OR articles_log.source_table <> 'contents') from second part (news) since we know it's allways true because OR articles_log.source_table <> 'contents' is allways true.
Remove the joins with contents and news. You can join the *_trans tables directly using record_id
Remove articles_log.dat > 0 since it's redundant with articles_log.dat >= 1488319200
The resulting query:
SELECT (
SELECT COUNT(*)
FROM articles_log
INNER JOIN `contents_trans`
ON `contents_trans`.record_id = articles_log.record_id
AND `contents_trans`.lang='lv'
WHERE articles_log.bot = '0'
AND articles_log.dat >= 1488319200
AND articles_log.dat <= 1489355999
AND articles_log.record_id NOT LIKE '%\_404'
AND articles_log.record_id <> '404'
) + (
SELECT COUNT(*)
FROM articles_log
INNER JOIN `news_trans`
ON `news_trans`.record_id = articles_log.record_id
AND `news_trans`.lang='lv'
WHERE articles_log.bot = '0'
AND articles_log.dat >= 1488319200
AND articles_log.dat <= 1489355999
) AS cnt
Try the following index combinations:
articles_log(bot, dat, record_id)
contents_trans(lang, record_id)
news_trans(lang, record_id)
or
contents_trans(lang, record_id)
news_trans(lang, record_id)
articles_log(record_id, bot, dat)
It depends on the data, which combination ist the better one.
I might be wrong on one ore more points, since i don't know your data and business logic. If so, try to adjust the other.
You can get the calculation when you run the query using SQL_CALC_FOUND_ROWS as explained in the documentation:
select SQL_CALC_FOUND_ROWS *
. . .
And then running:
select FOUND_ROWS()
However, the first run needs to generate all the data, so you are going to get up to 20 possible rows -- I don't think it respects LIMIT in subqueries.
Given the structure of your query and you want to do, I would think first about optimizing the query. For instance, is UNION really needed (it incurs overhead for removing duplicates)? As pointed out in a comment, your joins are really inner joins disguised as outer joins. Indexes might improve performance.
You might want to ask another question, providing sample data and desired results to get advice on such issues.
Some sql query gives me the following result:
As you can see, it already has GROUP BY.
So what I need? I need to group it again (by treatment_name) and count rows for each group. See more details on screenshot.
Here is full query:
SELECT
treatment_summaries.*
FROM `treatment_summaries`
INNER JOIN
`treatments`
ON
`treatments`.`treatment_summary_id` = `treatment_summaries`.`id`
AND
(treatment <> '' and treatment is not null)
INNER JOIN
`treatment_reviews`
ON
`treatment_reviews`.`treatment_id` = `treatments`.`id`
INNER JOIN
`conditions_treatment_reviews`
ON
`conditions_treatment_reviews`.`treatment_review_id` = `treatment_reviews`.`id`
INNER JOIN
`conditions` ON `conditions`.`id` = `conditions_treatment_reviews`.`condition_id`
INNER JOIN `conditions_treatment_summaries` `conditions_treatment_summaries_join`
ON
`conditions_treatment_summaries_join`.`treatment_summary_id` = `treatment_summaries`.`id`
INNER JOIN `conditions` `conditions_treatment_summaries`
ON `conditions_treatment_summaries`.`id` = `conditions_treatment_summaries_join`.`condition_id`
WHERE
`conditions`.`id` = 9
AND `conditions`.`id` IN (9)
AND (latest_review_id is not null)
GROUP BY
treatment_reviews.id
ORDER BY
treatment_summaries.reviews_count desc
LIMIT 20 OFFSET 0
Maybe there is another issue, cause GROUP BY should not leave same lines (for given column), but anyway you can wrap it like this:
SELECT * FROM ( YOUR_SQL_SELECT_WITH_EVERYTHING ) GROUP BY id
So the result you get will behave as another table and you can do all operations like GROUP BY again.
Everything in the following query results in one line for each invBlueprintTypes row with the correct information. But I'm trying to add something to it. See below the codeblock.
Select
blueprintType.typeID,
blueprintType.typeName Blueprint,
productType.typeID,
productType.typeName Item,
productType.portionSize,
blueprintType.basePrice * 0.9 As bpoPrice,
productGroup.groupName ItemGroup,
productCategory.categoryName ItemCategory,
blueprints.productionTime,
blueprints.techLevel,
blueprints.researchProductivityTime,
blueprints.researchMaterialTime,
blueprints.researchCopyTime,
blueprints.researchTechTime,
blueprints.productivityModifier,
blueprints.materialModifier,
blueprints.wasteFactor,
blueprints.maxProductionLimit,
blueprints.blueprintTypeID
From
invBlueprintTypes As blueprints
Inner Join invTypes As blueprintType On blueprints.blueprintTypeID = blueprintType.typeID
Inner Join invTypes As productType On blueprints.productTypeID = productType.typeID
Inner Join invGroups As productGroup On productType.groupID = productGroup.groupID
Inner Join invCategories As productCategory On productGroup.categoryID = productCategory.categoryID
Where
blueprints.techLevel = 1 And
blueprintType.published = 1 And
productType.marketGroupID Is Not Null And
blueprintType.basePrice > 0
So what I need to get in here is the following table with the columns below it so I can use the values timestamp and sort the entire result by profitHour
tablename: invBlueprintTypesPrices
columns: blueprintTypeID, timestamp, profitHour
I need this information with the following select in mind. Using a select to show my intention of the JOIN/in-query select or whatever that can do this.
SELECT * FROM invBlueprintTypesPrices
WHERE blueprintTypeID = blueprintType.typeID
ORDER BY timestamp DESC LIMIT 1
And I need the main row from table invBlueprintTypes to still show even if there is no result from the invBlueprintTypesPrices. The LIMIT 1 is because I want the newest row possible, but deleting the older data is not a option since history is needed.
If I've understood correctly I think I need a subquery select, but how to do that? I've tired adding the exact query that is above with a AS blueprintPrices after the query's closing ), but did not work with a error with the
WHERE blueprintTypeID = blueprintType.typeID
part being the focus of the error. I have no idea why. Anyone who can solve this?
You'll need to use a LEFT JOIN to check for NULL values in invBlueprintTypesPrices. To mimic the LIMIT 1 per TypeId, you can use the MAX() or to truly make sure you only return a single record, use a row number -- this depends on whether you can have multiple max time stamps for each type id. Assuming not, then this should be close:
Select
...
From
invBlueprintTypes As blueprints
Inner Join invTypes As blueprintType On blueprints.blueprintTypeID = blueprintType.typeID
Inner Join invTypes As productType On blueprints.productTypeID = productType.typeID
Inner Join invGroups As productGroup On productType.groupID = productGroup.groupID
Inner Join invCategories As productCategory On productGroup.categoryID = productCategory.categoryID
Left Join (
SELECT MAX(TimeStamp) MaxTime, TypeId
FROM invBlueprintTypesPrices
GROUP BY TypeId
) blueprintTypePrice On blueprints.blueprintTypeID = blueprintTypePrice.typeID
Left Join invBlueprintTypesPrices blueprintTypePrices On
blueprintTypePrice.TypeId = blueprintTypePrices.TypeId AND
blueprintTypePrice.MaxTime = blueprintTypePrices.TimeStamp
Where
blueprints.techLevel = 1 And
blueprintType.published = 1 And
productType.marketGroupID Is Not Null And
blueprintType.basePrice > 0
Order By
blueprintTypePrices.profitHour
Assuming you might have the same max time stamp with 2 different records, replace the 2 left joins above with something similar to this getting the row number:
Left Join (
SELECT #rn:=IF(#prevTypeId=TypeId,#rn+1,1) rn,
TimeStamp,
TypeId,
profitHour,
#prevTypeId:=TypeId
FROM (SELECT *
FROM invBlueprintTypesPrices
ORDER BY TypeId, TimeStamp DESC) t
JOIN (SELECT #rn:=0) t2
) blueprintTypePrices On blueprints.blueprintTypeID = blueprintTypePrices.typeID AND blueprintTypePrices.rn=1
You don't say where you are putting the subquery. If in the select clause, then you have a problem because you are returning more than one value.
You can't put this into the from clause directly, because you have a correlated subquery (not allowed).
Instead, you can put it in like this:
from . . .
(select *
from invBLueprintTypesPrices ibptp
where ibtp.timestamp = (select ibptp2.timestamp
from invBLueprintTypesPrices ibptp2
where ibptp.blueprintTypeId = ibptp2.blueprintTypeId
order by timestamp desc
limit 1
)
) ibptp
on ibptp.blueprintTypeId = blueprintType.TypeID
This identifies the most recent records for all the blueprintTypeids in the subquery. It then joins in the one that matches.