Storm Spirit Storm Spirit - 4 months ago 8
MySQL Question

How to combine two query from the same table

I have two query and I want to combine them into one query and distinct the

name
of the
styles
. Basically I just want to get the styles of the
teacher
where he belong on
schools
, and the
styles
of the
organization
where the
school
belong.

This is my query each so far.

STYLES Table

enter image description here

Query 1

SELECT *
FROM styles s
WHERE s.organization_id = (
SELECT t.school_id
FROM teachers t
WHERE t.user_id = 4
)


Result 2
enter image description here

Query 2

SELECT *
FROM styles s, teachers t
WHERE t.school_id = s.school_id
AND t.user_id = 4


Result 2
enter image description here

Answer

You are just lacking proper joins with your queries. Don't user old join styles, use INNER JOIN

For what I could see you have joined your styles table with teachers table by different columns. One way to do it would be a simple UNION like this:

SELECT * 
  FROM styles s
         INNER JOIN teachers t
               ON s.organization_id = t.school_id
 WHERE t.user_id = 4
UNION
SELECT * 
  FROM styles s
         INNER JOIN teachers t 
               ON t.school_id = s.school_id 
 WHERE t.user_id = 4

**NOTE: ** Do not use select * use all named columns.

Comments