Search code examples
mysqlsqljoinsubquerywhere-clause

SQL join with the same table with different select


I have a table tablename with columns col1-col10. Not every row has col4 populated, but every row has col1, col2, col3 populated. I want to get all {col1, col2, col3} tuples for when col4 satisfies a condition, then get all rows that match the tuple {col1, col2, col3} from tablename.

I am not sure if I should be using inner join or left join or something else? ( I think both inner and left join should give me same result) The query below gives me a syntax error "mismatched input AS". What is the correct way to write this query?

select col1, col2, col3
from tablename 
where col4 >= 1000 AS A
INNER JOIN
(select *
FROM tablename) AS B
ON A.col1 = B.col1 AND A.col2 = B.col2 A.col3 = B.col3

Solution

  • You can use exists:

    select t.*
    from mytable t
    where exists (
        select 1
        from mytable t1
        where 
            t1.col1 = t.col1 
            and t1.col2 = t.col2 
            and t1.col3 = t.col3 
            and t1.col4 >= 1000
    )