sql >> Database teknologi >  >> RDS >> Mysql

Hvordan sorteres resultatet af flere forespørgsler alternativt?

Sådan kan du gøre dette

select @rn:[email protected]+1 as id,colors from (
  (select @rn1:= @rn1+1 as rn,colors from table1,(select @rn1:=0)x order by id )
   union all 
  (select @rn2:= @rn2+1 as rn,numbers as colors from table2,(select @rn2:=0.5)x order by id)
   union all 
  (select @rn3:= @rn3+1 as rn,names as colors from table3,(select @rn3:=0.6)x order by id )
)x,(select @rn:=0)y order by rn ;

Ideen er at tildele en rn værdi for hvert tabelelement og skal sikre, at disse værdier altid er i stigende rækkefølge

Så hvis du kører forespørgslen for hver tabel, du har

mysql> select @rn1:= @rn1+1 as rn,colors from table1,(select @rn1:=0)x order by id;
+------+--------+
| rn   | colors |
+------+--------+
|    1 | red    |
|    2 | green  |
|    3 | blue   |
|    4 | yellow |
+------+--------+
4 rows in set (0.00 sec)

mysql> select @rn2:= @rn2+1 as rn,numbers as colors from table2,(select @rn2:=0.5)x order by id;
+------+--------+
| rn   | colors |
+------+--------+
|  1.5 | ten    |
|  2.5 | two    |
|  3.5 | one    |
|  4.5 | three  |
|  5.5 | six    |
|  6.5 | five   |
+------+--------+
6 rows in set (0.00 sec)

mysql> select @rn3:= @rn3+1 as rn,names as colors from table3,(select @rn3:=0.6)x order by id;
+------+--------+
| rn   | colors |
+------+--------+
|  1.6 | jack   |
|  2.6 | peter  |
+------+--------+
2 rows in set (0.00 sec)

Her kan du se table1 rn værdier er 1,2,3,.... table2 værdier er 1.5,2.5,3.5,.... table3 værdier er 1.6,2.6,....

så endelig når du bestiller resultatet med alle rn bliver det som

1,1.5,1.6,2,2.5,2.6,....




  1. Sådan benchmarker du Moodles ydeevne

  2. PostgreSQL Connection Pooling:Del 2 – PgBouncer

  3. Ændre udførelsesplanen for forespørgslen i postgresql manuelt?

  4. MAX() i ORACLE SQL