Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select data from subquery mysql

select t1.table1 from table1 as t1
where t1.column1 
in 
(
    select t2.column2 from table2 as t2 
    join 
    table3 as t3  on t2.column1=t3.column1 
    where t3.columnx=5
);

Above is the mysql query i am firing. Wanted some data from the subquery tables also.

For example say columnxy from table t2.

query that fails

select t1.table1,t2.columnxy from table1 as t1
where t1.column1 
in 
(
    select t2.column2 from table2 as t2 
    join 
    table3 as t3  on t2.column1=t3.column1 
    where t3.columnx=5
);

If i add them with select of the outer query gives error "unknown column" which does make sense.

Is the right way or should rewrite query with joins?

like image 484
amitchhajer Avatar asked Mar 16 '26 01:03

amitchhajer


1 Answers

Rewrite the query with joins:

SELECT t1.table1, t.columnxy
FROM   table1 AS t1 JOIN (
  SELECT t2.column2, t2.columnxy
  FROM   table2 AS t2 JOIN table3 AS t3 USING (column1)
  WHERE  t3.columnx = 5
) t ON t1.column1 = t.column2

Or:

SELECT t1.table1, t2.columnxy
FROM   table1 AS t1
  JOIN table2 AS t2 ON t1.column1 = t2.column2
  JOIN table3 AS t3 ON t2.column1 = t3.column1
WHERE  t3.columnx = 5
like image 136
eggyal Avatar answered Mar 18 '26 15:03

eggyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!