Skip to content
Advertisement

Left join without using view

I have a table structure similar to this:

users

| id |  name  |
|----|--------|
|  1 |  jane  |
|  2 |  john  |

client

| id |    name    | user_id |
|----|------------|---------|
|  1 |  client  1 |    2    |
|  2 |  client  2 |    2    |
|  3 |  client  3 |    2    |
|  4 |  client  4 |    1    |
|  5 |  client  5 |    1    |

products

| id |    name    | user_id |
|----|------------|---------|
|  1 |  product 1 |    1    |
|  2 |  product 2 |    1    |
|  3 |  product 3 |    1    |
|  4 |  product 4 |    2    |
|  5 |  product 5 |    2    |

and I also created two views

client_total

| user_id | client_total |
|---------|--------------|
|  1      |       2      |
|  2      |       3      |

products_total

| user_id |products_total|
|---------|--------------|
|  1      |       3      |
|  2      |       2      |

and that was a result

| id |  name  |products_total| client_total |
|----|--------|--------------|--------------|
|  1 |  jane  |       3      |       2      |
|  2 |  john  |       2      |       3      |

My question is:

Can I get this same result without using these two views?

Advertisement

Answer

GROUP BY in derived tables (the subqueries), before you LEFT JOIN:

(Doesn’t even some people call these derived tables inline views?)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement