来自不同表的行在一行sql中

时间:2017-09-05 11:10:48

标签: mysql sql database-performance

我正在寻找一种解决方案,将1个查询中的3个选择查询组合在一起,以优化我们产品的速度,减少数据库的等待时间。情况就是这样:

有3个表

第一个表(雇主):
*ID  username*
1   employerFirst
2   employerSecond
3   omployerThird
第二个表(员工):
*ID  username*
1   employeeFirst
2   employeeSecond
3   employeeThird
最后一张桌子(第三部分):
*ID  username*
1   partFirst
2   partSecond
3   partThird

我需要什么:

*username*
employerFirst
employerSecond
employerThird
employeeFirst
employeeSecond
employeeThird
partFirst
partSecond
partThird

2 个答案:

答案 0 :(得分:3)

使用UNION ALLUNION

UNION会删除重复项,而UNION ALL会保留重复值 取决于你正在接近什么。

    SELECT username FROM employer
 UNION ALL
    SELECT username FROM employee
 UNION ALL
    SELECT username FROM third_Part

或者如果您不想返回重复值:

    SELECT username FROM employer
     UNION 
    SELECT username FROM employee
     UNION 
    SELECT username FROM third_Part

答案 1 :(得分:2)

使用UNION

SELECT username FROM employer
UNION
SELECT username FROM employee
UNION
SELECT username FROM third_part