0

I have 2 select statements:

  1. timestamp of emp getting awards for specific emp id

    SELECT * FROM user_table,employeetable,awards where user_table.empid=employeetable.empid AND user_table.empid=awards.empid AND user_table.empid=123 ORDER BY timestamp DESC

  2. All employees staying around 25 miles from the current loc:current location: lat =37 lng=-122

    SELECT * ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) )+ sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM user_table,employeetable,awards where user_table.empid=employeetable.empid AND user_table.empid=awards.empid HAVING distance < 25 ORDER BY distance;

How do I combine both and ORDER BY timestamp ?btw both have field timestamp.

1.has specific user
2.all users within specific radius

I really appreciate any help.Thanks in Advance.

0

1 Answer 1

1

You can combine the two queries into a single query, just using logic in the where clause (which this has turned into a having clause:

select *, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) )+ sin( radians(37) ) * sin( radians( lat ) ) ) ) as distance
from user u join
     employee e
     on u.empid = e.empid join
     awards a
     on u.empid = a.empid
having empid = 123 or distance < 25;

This uses having instead of where so the distance column alias can be used instead of the formula.

Sign up to request clarification or add additional context in comments.

7 Comments

what if there are more empid. ie: instead of only 123 I have 123,234,567,789,102 .Then will the code above change to IN ?basically when i have group of empids.
Yes, you would have empid in (123, 234, 567, 789, 102) as the first condition.
so I need to replace empid=123 to empid in (123, 234, 567, 789, 102) with HAVING behind empid thats it?
Yes. That is the way.
query:SELECT * FROM ( SELECT * FROM user u INNER JOIN employee e ON (u.empid = e.empid) INNER JOIN awards a ON (u.empid = a.empid) WHERE u.empid = 123 UNION SELECT * ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) )+ sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM user u INNER JOIN employee e ON (u.empid = e.empid) INNER JOIN awards a ON (u.empid = a.empid) HAVING distance < 25 ORDER BY distance ) a ORDER BY timestamp DESC error "The used SELECT statements have a different number of columns
|

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.