0

I need to do selection from mysql 5.7.22 in one query.

select id from t1 where type_id=(select type_id from t2 where id=1 limit 1) and id not in  
            (select obj_id from t2
                where 
                    type_id = (select type_id from t2 where id=1 limit 1)
                    and
                    type2_id = (select type2_id from t2 where id=1 limit  
                    ...
             ) 

I have some duplicate subquerys in where clause (it's only part of the query, this subquery duplicates many times)

'(select type_id from t2 where id=1 limit 1)'

Can I some how figure it out in one place, to reduce verbose. So I want to select once

select type_id, type2_id from t2 where id=1 limit 1

and make type_id, type2_id available in all query context.

I know mysql 8.0 has WITH syntax, but I am using 5.7.22

I want to do this in one query without transactions.

2 Answers 2

1

It's hard to give you complete advice without seeing your more of your query. But you have some choices.

You could try creating a view as follows then using it.

CREATE VIEW selector
    AS SELECT MAX(type_id) type_id, MAX(obj_id) obj_id
         FROM t2
        WHERE id = 1

It looks possible that the t2 query returns multiple rows. This view deals with that by using MAX() instead of LIMIT 1. But if t2.id is a primary key, then all you need is

CREATE VIEW selector
    AS SELECT type_id, obj_id
         FROM t2
        WHERE id = 1

Then you can use the view in your query.

For example

SELECT id
  FROM t1
 WHERE type_id = (SELECT type_id FROM selector)
   AND obj_id <> (SELECT obj_id FROM selector)

Or you could figure out how to use join operations rather than subqueries.

SELECT id
  FROM t1
  JOIN selector ON t1.type_id = selector.type_id AND t1.obj_id <> selector.obj_id
Sign up to request clarification or add additional context in comments.

Comments

0

try this

select id from t1 ,(select type_id from t2 where id=1 limit 1)  t where type_id=t.type_id and id not in  
            (select obj_id from t2
                where 
                    type_id = t.type_id 
                    and
                    type2_id = t.type_id   
                    ...
             ) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.