MySQL:是否可以返回“混合”数据?数据集?
我想知道 MySQL 中是否有一些聪明的方法可以根据特定标准返回“混合/平衡”数据集?
为了说明这一点,假设表中存在类型 1 或类型 2 的潜在结果(即,每条记录的列的值为 1 或 2)。是否有一个聪明的查询能够直接按顺序返回 1 和 2 之间交替的结果:
第一个记录的类型为 1, 第二条记录属于类型 2, 第 3 条记录属于类型 1, 第 4 条记录属于类型 2, 等等...
如果问题很愚蠢,我只是在寻找一些选择。当然,我可以返回任何数据并在 PHP 中执行此操作,但它确实添加了一些代码。
谢谢。
I'm wondering if there's some clever way in MySQL to return a "mixed/balanced" dataset according to a specific criterion?
To illustrate, let's say that there are potential results in a table that can be of Type 1 or Type 2 (i.e. a column has a value 1 or 2 for each record). Is there a clever query that would be able to directly return results alternating between 1 and 2 in sequence:
1st record is of type 1,
2nd record is of type 2,
3rd record is of type 1,
4th record is of type 2,
etc...
Apologies if the question is silly, just looking for some options. Of course, I could return any data and do this in PHP, but it does add some code.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的查询应该执行以下操作:
它将唯一的偶数分配给
x=0
,将奇数分配给x=1
,并使用这些值作为排序条件。它返回
以下测试数据:
在交替规则中,值按
some_value
排序,您可以在内部选择中更改此设置,或在其中添加条件。如果某种类型有更多值(
1
或2
),您将在其余值之后获取它们(1 2 1 2 2 2
) 。Something like this query should do:
It assigns unique even numbers to
x=0
, and odd numbers tox=1
, and uses these values as sort criteria.It returns
for the following test-data:
Within the alternating rule values are sorted by
some_value
, you can change this in the inner select, or add your conditions there.If there are more values of a certain type (
1
or2
), you get them after the rest (1 2 1 2 2 2
).您可以使用 IF 函数作为 SELECT 语句的一部分来更改列,但我不确定如何在两列之间自动交替。但是,如果您找到合适的条件,这将适合您
first_column
和second_column
可以是不同的类型,例如:当
name
是VARCHAR
和status_id
是INT
You can use IF function as a part of your SELECT statement to change columns, but I'm not sure how to make is alternate automatically between two columns. If you however find proper condition this will work for you
first_column
andsecond_column
can be of different type, for example:works well when
name
is aVARCHAR
andstatus_id
is anINT