包含每个表中随机值的表

时间:2012-05-09 11:04:41

标签: sql database

我有3个表.a,b,c。其数据类型为varchar的名称。我需要一个查询,从每个表中获取一行并给我另一个表即'd。这将有3行例如。 a1高于b3高于c2 ..每次运行此查询时,表d中的这些值都是随机的..

Table a   Table b   Table c
 Name      Name       Name
 a1        b1         c1
 a2        b2         c2 
 a3        b3         c3

当我运行查询时,我需要一个带有随机

的表'd'
Table d    Table d
 Name       Name
 a2         b1
 b3         a3
 c1         c3

这些表之间没有关系!

4 个答案:

答案 0 :(得分:0)

有很多方法可以从数据库表中选择随机记录或行。以下是一些不需要其他应用程序逻辑的示例SQL语句,但每个数据库服务器都需要不同的SQL语法。

使用 MySQL 选择一个随机行:

 SELECT column FROM table
ORDER BY RAND()
LIMIT 1

使用 PostgreSQL 选择一个随机行:

 SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

使用 Microsoft SQL Server 选择随机行:

SELECT TOP 1 column FROM table
ORDER BY NEWID()

使用 IBM DB2

选择随机行
 SELECT column, RAND() as IDX 
FROM table 
ORDER BY IDX FETCH FIRST 1 ROWS ONLY

使用 Oracle 选择随机记录:

 SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1

答案 1 :(得分:0)

以下查询将从每个表中返回一个随机行。

WITH  OneRandomRowFromA
    AS ( SELECT TOP 1
                 Name
               , RAND(CAST(NEWID() AS BINARY(6))) AS RandomNumber
         FROM    TableA
         ORDER BY 2
       ) ,
  OneRandomRowFromB
    AS ( SELECT TOP 1
                 Name
               , RAND(CAST(NEWID() AS BINARY(6))) AS RandomNumber
         FROM    TableB
         ORDER BY 2
       ) ,
  OneRandomRowFromC
    AS ( SELECT TOP 1
                 Name
               , RAND(CAST(NEWID() AS BINARY(6))) AS RandomNumber
         FROM    TableC
         ORDER BY 2
       )
SELECT   Name
FROM     OneRandomRowFromA
UNION ALL
SELECT   Name
FROM     OneRandomRowFromB
UNION ALL
SELECT   Name
FROM     OneRandomRowFromC

答案 2 :(得分:0)

试试希望它能帮到你

 ---- This will create a random number between 1 and 3           
   DECLARE @Random1 INT;
   DECLARE @Random2 INT;
   DECLARE @Random3 INT;
   DECLARE @Upper INT;
   DECLARE @Lower INT


SET @Lower = 1 ---- The lowest random number
SET @Upper = 4 ---- The highest random number
SELECT @Random1 = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)  
SELECT @Random2 = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)       
SELECT @Random3 = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0) 

--query here--
;with tableA AS
(
    SELECT Name,
    ROW_NUMBER() OVER (ORDER BY Name) AS RowNumber
    FROM a 
),  tableB AS
(
    SELECT Name,
    ROW_NUMBER() OVER (ORDER BY Name) AS RowNumber
    FROM b 
)
,tableC AS
(
    SELECT Name,
    ROW_NUMBER() OVER (ORDER BY Name) AS RowNumber
    FROM c 
)

select Name from tableA where RowNumber= @Random1 
union
 select Name from  tableB where  RowNumber=@Random2  
 union
 select Name from tableC where RowNumber=@Random3

答案 3 :(得分:0)

- 表D

select (select top 1 name from @TableA order by newid()) as Name
union all
select (select top 1 name from @TableB order by newid())
union all
select (select top 1 name from @TableC order by newid())