如何从2个表中选择不同的行

时间:2013-08-15 01:34:42

标签: mysql sql

我试图从2个不同字段的表中随机抽取3个不同的行

SELECT * FROM `models` JOIN banners WHERE `recomended` = '1' ORDER BY RAND() LIMIT 0,3

我想要一个这样的结果:

first row - table1.id table1.name table1.points
second row - table2.id table2.group table.2points
third row - table1.id table1.name table1.points

有可能吗?

1 个答案:

答案 0 :(得分:0)

以下是获得所需内容的一种方法:

select id, name, points
from ((select  id, name, points, 1 as which
       from table1
       order by rand()
       limit 1
      ) union all
      (select  id, group, points, 2 as which
       from table2
       order by rand()
       limit 1
      ) union all
      (select  id, name, points, 3 as which
       from table1
       order by rand()
       limit 1
      )
     ) t
order by which;