简体   繁体   English

如何实现SQL语句来创建/或功能

[英]How to implement SQL statement to create either/or functionality

SQL statement question. SQL语句问题。 Let's say I have the following in my mini-table. 假设我的迷你表中有以下内容。 Let's say the table is "images." 假设该表是“图像”。

ID  |  file_name   |fruit_type | 
================================
1   |     ex.jpg   |  apple    | 
2   |     am.png   |  apple    | 
3   |     pl.jpeg  |  orange   |  
4   |      e.png   |  orange   | 
5   |     yep.png  |  apple    |

OK. 好。 So when I call this, I want it to pull two pictures, and each should be a random selection from within a fruit_type. 所以当我打电话给这个时,我希望它能够拉出两张图片,每张图片应该是一个来自fruit_type的随机选择。 So apples should only be picked with apples. 所以苹果应该只用苹果挑选。 Oranges should only be picked with oranges. 橘子应该只用橙子挑选。 There should be no combination of both types. 应该没有两种类型的组合。

Here's where it breaks down. 这是它崩溃的地方。 Let's say the code I run is this: 假设我运行的代码是这样的:

$query="SELECT * FROM images WHERE fruit_type='apple' 
OR fruit_type='orange' ORDER BY RAND() LIMIT 0,2";

This would return two random selections, like I want. 这会返回两个随机选择,就像我想要的那样。 However, this captures BOTH apple and orange types from that column. 但是,这会从该列中捕获苹果和橙子类型。

I have been trying to identify an SQL statement that would allow it to either choose apples or oranges, but never both. 我一直在尝试识别一个SQL语句,它允许它选择苹果或橙子,但从不两者。 I've come up short, so I'm turning to you all. 我很短暂,所以我转向你们所有人。

您可以创建两个查询,首先是苹果,第二个是橙子,然后选择随机苹果和随机橙色,然后使用UNION ALL子句加入它们。

The following will work, but it won't be a great option from a performance point of view if your table gets huge (millions of records). 以下内容可行,但从性能的角度来看,如果您的表变得庞大(数百万条记录),它将不是一个很好的选择。 The below query takes all combinations of images that have the same fruit_type excluding matching images (you don't want the same image twice, do you?). 以下查询采用具有相同fruit_type但不包括匹配图像的所有图像组合(您不希望同一图像两次,是吗?)。

SELECT images1.*, images2.*
FROM images images1, images images2
WHERE images1.id != images2.id
AND images1.fruit_type = images2.fruit_type
ORDER BY RAND()
LIMIT 0,2

Since you don't have windowing functions in MySQL, you have to improvise. 由于您在MySQL中没有窗口函数,因此您必须即兴发挥。 This post is adapted from this blog post by Quassnoi : 这篇文章改编自Quassnoi的博客文章

  SELECT  
    distinct
    @fi AS file_name,
    fruit_type

    FROM    (
    SELECT  m.*
    FROM    (

    SELECT  @_f = NULL

    ) vars,

    images m
    ORDER BY
    fruit_type, rand()
    ) mo

    WHERE   (CASE WHEN @_f IS NULL OR @_f <> fruit_type THEN @fi := file_name ELSE file_name END IS NOT NULL)

    AND (@_f := fruit_type) IS NOT NULL

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

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