左加入单个随机记录MySQL

时间:2017-02-12 01:39:49

标签: mysql

我试图从加入Sponsor表的Company表中随机获取一行。跟随查询几乎有效,但有时会返回NULL赞助商。

谁能看到我在这里做错了什么?

SELECT C.ID AS CompID, C.Name AS CompName, S.ID AS SponID, S.Name AS SponName 
FROM Company C 
     LEFT JOIN Sponsor S ON S.ID = (SELECT ID FROM Sponsor WHERE Company = C.ID ORDER BY RAND() LIMIT 1)

数据样本:

Company Table
| ID | Name      |
|  1 | MyCompany |

Sponsor Table
| ID | Company | Name    |
|  1 |     1   | Bruce   |
|  2 |     1   | John    |

在以下某项中查询结果:

| CompID | CompName  | SponsID | SponName |
|    1   | MyCompany |    1    |  Bruce   |

| CompID | CompName  | SponsID | SponName |
|    1   | MyCompany |    2    |  John    |

| CompID | CompName  | SponsID | SponName |
|    1   | MyCompany |  NULL   |  NULL    |

2 个答案:

答案 0 :(得分:1)

由于RAND(),您的子查询不具有确定性,因此会对Sponsor表中的每一行执行,并且每次都返回一个随机ID,该ID可能与当前行的ID匹配或不匹配。所以不仅没有行可以匹配随机ID。它也可能是多行。

对于具有两个赞助商的样本数据,子查询可能会返回以下值:

  • (1,1)将匹配第一行(1 = 1,2 = 1)
  • (1,2)将匹配两行(1 = 1,2 = 2)
  • (2,1)将匹配无行(1 = 2,2 = 1)
  • (2,2)将匹配第二行(1 = 2,2 = 2)

为了保证子查询只执行一次,可以使用SELECT子句。然后将结果作为派生表与Sponsor表连接:

SELECT C.*, S.Name AS SponName 
FROM (
    SELECT C.ID AS CompID, C.Name AS CompName, (
        SELECT ID FROM Sponsor WHERE Company = C.ID ORDER BY RAND() LIMIT 1
    ) as SponID
    FROM Company C
) C
LEFT JOIN Sponsor S ON S.ID = C.SponID

演示:http://rextester.com/LSSJT25902

答案 1 :(得分:0)

您的查询看起来很好,不知道为什么它不起作用。

尝试使用 ORDER BY UUID() 。我的情况是每次生成1行(非空)。