A
A
Anastasia2021-07-27 14:03:29
SQL
Anastasia, 2021-07-27 14:03:29

Is it possible to get 2 records at once in a query, by a parameter that is known in 1?

Hello. The question in the title is very chaotic, but it's not so difficult there.
Is it possible to fit this construction into one request:
I need to get the record with id 127 and the previous record, where mytarget is equal to what is in 127. In fact, two queries can be made:

SELECT result, mytarget FROM mydata WHERE id = '127' ORDER BY id DESC LIMIT 1
SELECT result FROM mydata WHERE id < '127' AND mytarget=$db['mytarget'] ORDER BY id DESC LIMIT 1

But I wanted to clarify whether one query would be faster? And is it even possible?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BorLaze, 2021-07-27
@nastya97core

Exactly two or the first one is needed insofar as the mytarget field from it is needed?
If only the last request is important, you can do this

SELECT result 
FROM mydata 
WHERE id < '127' AND mytarget = (SELECT mytarget FROM mydata WHERE id = '127')
ORDER BY id DESC 
LIMIT 1

If both strings are needed, then UNION
SELECT result, mytarget 
FROM mydata 
WHERE id = '127'

UNION 

SELECT result, mytarget 
FROM mydata 
WHERE id < '127' AND mytarget = (SELECT mytarget FROM mydata WHERE id = '127')
ORDER BY id DESC 
LIMIT 1

As for faster, it's hard to say; but usually two requests take longer than one, albeit a complex one.

T
ThunderCat, 2021-07-27
@ThunderCat

Taking into account the layer in the form of some kind of server language, connection and passing request parameters - one request will be faster, not much, but yes, faster.

SELECT * 
FROM mydata 
WHERE id < '127' 
AND mytarget = (
   SELECT mytarget 
   FROM mydata 
   WHERE id = '127' 
   ORDER BY id DESC 
   LIMIT 1
) 
ORDER BY id DESC 
LIMIT 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question