2

我有 2 张桌子:

tb_a                  tb_2
==================    ===================
|id| data1 |rank |    |id| data2 | rank | 
==================    ===================
|1 | data1 |  1  |    | 1|  dataa|  1   | 
|2 | data2 |  2  |    | 2|  datab|  2   | 
etc..

数据将根据排名进行排序。结果必须是:

data1
dataa
data2
datab

编码 :

$query1= mysql_query("SELECT * FROM tb_a ORDER BY rank ASC");
while ($row1 = mysql_fetch_array($query1)) {
    $data = $row1['data1'];
    echo '<h2 class="title" > '.$data.'  </h2>';
}

$query2= mysql_query("SELECT * FROM tb_b ORDER BY rank ASC");
while ($row2 = mysql_fetch_array($query2)) {
    $data = $row2['data2'];
     echo '<h2 class="title" > '.$data.'  </h2>';
}

结果 :

data1
data2
dataa
datab

如何对它们进行排序取决于排名?谢谢你 :)

4

1 回答 1

4

您可以UNION在查询中使用一次请求数据库。

SELECT *
FROM
(
    SELECT id, data1 as `data`, rank
    FROM tb_a
    UNION ALL
    SELECT id, data2 as `data`, rank
    FROM tb_2
) x
ORDER BY x.rank ASC
于 2012-10-21T18:01:03.683 回答