从MySQL上的两个不同表中获取行,两个表之间没有任何关系

时间:2014-11-11 04:13:12

标签: php mysql

两个表之间有两个表,也没有关系,

结构:table_one

+---------+--------+-----------+
| name    | age    |insertTEMP |
+---------+--------+-----------+
| cat     | 12     |02-02-2014 |
| dog     | 13     |03-04-2014 |
+---------+--------+-----------+

结构:table_two

+---------+--------+---------------+
| book    | pages  | insertTEMP    |
+---------+--------+---------------+
| book1   | 34     | 05-02-2014    |
| book2   | 54     | 04-03-2014    |
+---------+--------+---------------+

现在我的想法是在这里,我想列出两个表中的记录,所以我保持下面的功能列出它们。

public function recentALL() {
   $sql = "select * from table_one, table_two ORDER BY insertTEMP";
    $q = $this -> conn -> prepare($sql);
    $q -> execute();
    return $row = $q -> fetchAll();
 }

我在视图中获取它,

        $data2 = $functions->recentAll();
            foreach ($data2 as $data3){
                  echo $data3['name']  . $data3['book'] . '<br />';

           }

我怎么能让它显示如下:

+---------+--------+
| cat     | NULL   |
| null    | book1  |
| null    | book2  |
| dog     | null   |
+---------+--------+

这基于 insertTEMP

1 个答案:

答案 0 :(得分:0)

使用以下查询

Select * from (
    Select name  as Name, null as Book,insertTEMP  from table_one
    UNION ALL
    select null as Name, book as Book,insertTEMP  from table_two
) as tmp
Order by tmp.insertTEMP asc

根据查询

更改代码中的列名称