简体   繁体   English

SQL获取玛丽亚数据库中的每个类别数据

[英]SQL for getting each category data in maria db

I need to fetch 4 random values from each category. 我需要从每个类别中获取4个随机值。 What should be the correct sql syntax for maria db. 什么是maria db正确的SQL语法。 I have attached one image of table structure. 我已附上一张表结构的图像。

Please click here to check the structure 请点击这里检查结构

Should i write some procedure or i can do it with basic sql syntax? 我应该编写一些过程还是可以用基本的SQL语法来完成?

You can do that with a SQL statement if you only have a few rows: 如果只有几行,则可以使用SQL语句执行此操作:

SELECT id, question, ... FROM x1 ORDER BY rand() LIMIT 1

This works fine if you have only a few rows - as soon as you have thousands of rows the overhead for sorting the rows becomes important, you have to sort all rows for getting only one row. 如果只有几行,这很好用-一旦拥有数千行,对行进行排序的开销就变得很重要,则必须对所有行进行排序以仅获得一行。

A trickier but better solution would be: 一个更棘手但更好的解决方案是:

SELECT id, question from x1  JOIN (SELECT CEIL(RAND() * (SELECT(MAX(id)) FROM x1)) AS id) as id using(id);

Running EXPLAIN on both SELECTS will show you the difference... 在两个SELECTS上运行EXPLAIN会显示出区别...

If you need random value for different categories combine the selects via union and add a where clause 如果您需要不同类别的随机值,请通过并集结合selects并添加where子句

http://mysql.rjweb.org/doc.php/groupwise_max#top_n_in_each_group http://mysql.rjweb.org/doc.php/groupwise_max#top_n_in_each_group

But then ORDER BY category, RAND() . 但是然后是ORDER BY category, RAND() (Your category is the blog's province .) (您的category是博客的province 。)

Notice how it uses @variables to do the counting. 注意它如何使用@variables进行计数。

If you have MariaDB 10.2, then use one of its Windowing functions. 如果您有MariaDB 10.2,请使用其Windowing功能之一。

SELECT column FROM table WHERE category_id = XXX 
ORDER BY RAND() 
LIMIT 4

do it for all categories 做到所有类别

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM