Search code examples
mysqlsqldatabase-performance

Rows from different tables in one row sql


I'm searching for a solution to combine 3 select query's in 1 query to optimize the speed of our product with reducing waiting time from the database. This is the situation:

There are 3 tables

the first table (employer):
*ID  username*
1   employerFirst
2   employerSecond
3   omployerThird
second table (employee):
*ID  username*
1   employeeFirst
2   employeeSecond
3   employeeThird
last table (third part):
*ID  username*
1   partFirst
2   partSecond
3   partThird

What I need:

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

Solution

  • Use UNION ALL or UNION.

    UNION removes duplicates, while UNION ALL will keep duplicate values.
    Depends on what you're approaching.

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

    or if you don't want to return duplicate values:

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