如何将两个MySQL列合并为一个列? [英] How to combine two MySQL columns to one column?

查看:944
本文介绍了如何将两个MySQL列合并为一个列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要转换此MySQL表:

I want to convert this MySQL table:

title1 | title2 |type  
-------+--------+----
qwe1   | qwe2   | 3  
asd1   | asd2   | 7

使用PHP到此表

title | type  
------+-----
asd1  | 7  
asd2  | 7  
qwe1  | 3  
qwe1  | 3

但是我不知道如何正确地按第一列排序PHP表.

But I don't know how to order the PHP table by the first column correctly.

(这是我当前正在使用的代码)

(This is the code I am currently using)

$sql = "SELECT * FROM table ORDER BY title1, title2";   
$pager = new PS_Pagination( $dbh, $sql, 3, 4, null );//pagination class
$rs = $pager->paginate(); 

while ($row = $rs->fetch(PDO::FETCH_ASSOC)){
    echo "<tr>";
    echo "<td>{$row['title1']}</td>";
    echo "<td>{$row['type']}</td>";
    echo "</tr>";

    echo "<tr>";
    echo "<td>{$row['title2']}</td>";
    echo "<td>{$row['type']}</td>";
    echo "</tr>";
}       

echo "</table>";

推荐答案

在SQL本身中,您可以使用UNION来完成.并在整个查询中使用ORDER BY

In SQL itself you can do it using UNION. And use ORDER BY for the whole query!

SELECT `title1` AS `title`, `type`
FROM `table`
UNION
SELECT `title2` AS `title`, `type`
FROM `table`
ORDER BY `title` ASC

输出

+-------+------+
| TITLE | TYPE |
+-------+------+
|  asd1 |    7 |
|  asd2 |    7 |
|  qwe1 |    3 |
|  qwe2 |    3 |
+-------+------+

这篇关于如何将两个MySQL列合并为一个列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆