MySQL JOIN查询结果有多行

时间:2016-09-07 07:42:54

标签: mysql sql

我有2个MySQL表

tbl_user

user_id | user_name
1       | John
2       | Kevin

tbl_admin

admin_id | admin_name
1        | Bob

SELECT `tbl_user`.`user_id` as `ID`, `tbl_user`.`user_name` as `NAME`, 
`tbl_admin`.`admin_id` as `ID`, `tbl_admin`.`admin_name` as `NAME` 
FROM `tbl_admin` INNER JOIN `tbl_user` ORDER BY `tbl_user`.`creation_date` DESC

以下是我上述查询的结果

ID | NAME  | ID | NAME
1  | John  | 1  | Bob
2  | Kevin | 1  | Bob

我希望结果采用以下格式

ID | NAME  |
1  | John  |
1  | Bob   |
2  | Kevin |

我可以为每个表编写单独的查询,但在这种情况下,表1结果将首先加载,然后表2结果,但我的目标是在ID或DATE的单个查询ORDER中获取两个TABLE结果。

2 个答案:

答案 0 :(得分:3)

使用UNION ALL

(SELECT user_id AS Id
    , user_name AS Name
    FROM tbl_user)

UNION ALL

(SELECT admin_id
    , admin_name
    FROM tbl_admin)

ORDER BY Id;

答案 1 :(得分:0)

    SELECT 
      user_id as Id, user_name as Name
      tbl_user   

        UNION

    SELECT admin_id
        , admin_name
        FROM tbl_admin

    ORDER BY Id;

使用UNION