[英]Get multiple rows from a table to per row of another table
I have a problem here, I wonder if it is possible to do this in just one query instead of having the server do several queries.我这里有一个问题,我想知道是否可以只在一个查询中执行此操作,而不是让服务器执行多个查询。
So here's the thing, what I want is, in each category, to search all stores belonging to that category within a limit of 24 stores.所以事情就是这样,我想要的是,在每个类别中,在 24 家商店的限制内搜索属于该类别的所有商店。 That is, imagining that I have 5 categories registered, I will search 24 stores belonging to that category, which in the conclusion I will have a total of 120 stores in the query result.也就是说,假设我注册了 5 个类别,我将搜索属于该类别的 24 家商店,最终我将在查询结果中总共有 120 家商店。
The following code is an example, but this will only fetch the first 24 stores of any category without iterating through each category.以下代码是一个示例,但这只会获取任何类别的前 24 个商店,而不会遍历每个类别。
SELECT *
FROM categories c
LEFT JOIN (SELECT * FROM stores_categories LIMIT 24 OFFSET 0) sc ON sc.id_category = c.id
WHERE type = 'STORE' OR type = 'ALL';
Someone sent me this and it is very similar to my problem, How to SELECT the newest four items per category?有人给我发了这个,它与我的问题非常相似, 如何 SELECT 每个类别的最新四个项目? , It is kind of like that, but I would like to be able to limit and with offset to make pages and not just the first 24 most recent in each category. ,有点像,但我希望能够限制和偏移来制作页面,而不仅仅是每个类别中的前 24 个最近的页面。
The example code from the link I was given:我给出的链接中的示例代码:
SELECT sc1.*
FROM stores_categories sc1
LEFT OUTER JOIN stores_categories sc2 ON (sc1.id_category = sc2.id_category AND sc1.id_store < sc2.id_store)
GROUP BY sc1.id_store
HAVING COUNT(*) < 24
ORDER BY sc1.id_category;
And the database server which one I'm is the version 5.5.64-MariaDB.我的数据库服务器是5.5.64-MariaDB版本。 An fiddle example where is possible to make tests with same values from my database.一个小提琴示例,可以使用我的数据库中的相同值进行测试。 https://www.db-fiddle.com/f/jcowJL9S4FQXqKg2yMa8kf/0 https://www.db-fiddle.com/f/jcowJL9S4FQXqKg2yMa8kf/0
It could make use of a calculated row_number per category.它可以利用每个类别的计算行数。
SELECT sc.id, id_store
, cat.name AS cat_name
, cat.type AS cat_type
, rn
FROM
(
SELECT sc.*
, @rn := CASE
WHEN @cat_id = sc.id_category
THEN @rn + 1 ELSE 1
END AS rn
, @cat_id := sc.id_category as cat_id
FROM stores_categories sc
CROSS JOIN (SELECT @cat_id:=0,@rn:=0) var
ORDER BY sc.id_category, sc.id DESC
) sc
JOIN categories cat
ON cat.id = sc.id_category
WHERE rn <= 24
Demo on db<>fiddle here关于 db<>fiddle 的演示在这里
Then to get another range, fe 25 - 48然后得到另一个范围,fe 25 - 48
... WHERE rn BETWEEN 25 AND 48
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.