Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL combine two queries

Tags:

mysql

I have two MySQL queries

QUERY:

SELECT sodnik_1 FROM prihodnji_krog  WHERE file_id='8778' AND sodnik_1 != ''
UNION 
SELECT sodnik_2 FROM prihodnji_krog  WHERE file_id='8778' AND sodnik_2 != ''
UNION
SELECT sodnik_3 FROM prihodnji_krog  WHERE file_id='8778' AND sodnik_3 != ''
UNION
SELECT sodnik_4 FROM prihodnji_krog  WHERE file_id='8778' AND sodnik_4 != ''

QUERY:
SELECT value FROM notification_sodniki WHERE user_id='16'

OUTPUT LOOKS LIKE THIS:

Name 1
Name 2
Name 3
Name 4

IN BOTH TABLES

They give me 1 column. I'd like to perform a cross join and return only the values that are present in both select queries. Is that possible ?

like image 594
litenull Avatar asked Nov 15 '12 15:11

litenull


1 Answers

How about

SELECT * FROM
(
    SELECT sodnik_1 as value FROM prihodnji_krog  WHERE file_id='8778' AND sodnik_1 != ''
    UNION 
    SELECT sodnik_2 as value FROM prihodnji_krog  WHERE file_id='8778' AND sodnik_2 != ''
    UNION
    SELECT sodnik_3 as value FROM prihodnji_krog  WHERE file_id='8778' AND sodnik_3 != ''
    UNION
    SELECT sodnik_4 as value FROM prihodnji_krog  WHERE file_id='8778' AND sodnik_4 != ''
) x INNER JOIN 
(
    SELECT value FROM notification_sodniki WHERE user_id='16'
) y 
ON x.value = y.value

When you use subqueries in a FROM clause, it's like if you are making temporary tables. Then with the alias you can refer to them and do a INNER JOIN

like image 175
Marc Avatar answered Sep 27 '22 16:09

Marc