Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combine two select statement in two column?

Tags:

mysql

i Have two select statement

1

select Start_Date
    from table1  where Start_Date not in (
    select End_Date
    from table1)

2

 select End_Date from table1
    where End_Date not in (
        select Start_Date
            from table1
        )

i want to combine two select statement in different column when i use union all it give me one column with the result of two queries i want each query result in different column but when i use inner join like that

select a.End_Date , b.Start_Date from
( select End_Date from table1
where End_Date not in (
select Start_Date
from table1
) ) a

join

(select Start_Date
from table1 where Start_Date not in (
select End_Date
from table1)
) b
on 1=1

it giving me result every record is repeating four times help me what i do next ??

like image 536
Muhammad Umar Avatar asked Feb 09 '23 13:02

Muhammad Umar


1 Answers

If each of your queries returns only 1 row you can use:

SELECT 
(select Start_Date
    from table1  where Start_Date not in (
        select End_Date
        from table1)
) AS StartDate,
 (select End_Date from table1
    where End_Date not in (
        select Start_Date
        from table1)
 ) AS EndDate

If your queries return more than 1 row you have to choose a different solution:

You can use UNION: (You'll have the two queries misaligned with "NULL" in the other column)

(select Start_Date, Null AS EndDate
    from table1  where Start_Date not in (
         select End_Date
         from table1)
) 
UNION
(select  Null As StartDate, End_Date 
    from table1
    where End_Date not in (
        select Start_Date
        from table1)
 ) 

You can use JOIN If you have a field to use as "Join On" you can use this field, if not you can add a field to join (but you need to check data returned to avoid errors) Also you have to check what kind of join may be good for you (Inner - Left - rigth) In the example I add a field to join and use an Inner Join:

SELECT Start_Date, End_Date
FROM
(select 1 as InnerId, Start_Date
    from table1  where Start_Date not in (
        select End_Date
        from table1)
) As Tab1
 INNER JOIN
 (select  1 as InnerId, End_Date from table1
    where End_Date not in (
        select Start_Date
        from table1)
 ) AS Tab2
USING(InnerId)
like image 71
genespos Avatar answered Feb 12 '23 11:02

genespos