Is it possible to connect to queries but get the results of first query before second one?

时间:2017-07-10 15:19:05

标签: mysql sql

I want to select users from my db based on their interests and country and then i want to select them based on interests only.So here is my queries

SELECT users.* 
FROM users 
JOIN user_opt ON users.id = user_opt.UserId 
WHERE user_opt.country IN(".implode(',',$Countries).")  AND user_opt.Hobbies REGEXP '".implode('|',$Interests)."'  LIMIT 100

SELECT users.* 
FROM users 
JOIN user_opt ON users.id = user_opt.UserId WHERE user_opt.country IN(".implode(',',$Countries).")  LIMIT 100

Now i want to join them into one query,but get the results of first query before second one's.

2 个答案:

答案 0 :(得分:0)

One probably solution can be

select * from 
    (select 1 AS sn, users.*
       ...
     union
     select 2 AS sn, users.*
       ...)
   order by sn;

答案 1 :(得分:0)

Use union all and order by if you want to guarantee that the first results come before the second:

(SELECT u.* , 1 as which
 FROM users u JOIN
      user_opt uo
      ON u.id = uo.UserId 
 WHERE u.country IN (".implode(',',$Countries).")  AND
       uo.Hobbies REGEXP '".implode('|',$Interests)."' 
 LIMIT 100
) UNION ALL
(SELECT u.*, 2 as which
 FROM users u JOIN
      user_opt uo
      ON u.id = uo.UserId
 WHERE uo.country IN(".implode(',',$Countries).") 
 LIMIT 100
)
ORDER BY which;