2017-12-17 14 views
0

これらの2つのSQLクエリを1つのクエリでマージするにはどうすればよいですか?merge 2 sqlクエリの場所と平均評価

$query2 ="select raiting.rated_user,avg(raiting.rate) as `avg_rating` from raiting,users where 
raiting.rated_user=user_id group by raiting.rated_user order by avg(raiting.rate) desc"; 

$query  = “SELECT `user_id`,`name`,`email`,`degree`,`avatar`,`mobile`,`sex`,`nationality`,`nationalitycode`,`birthday_year`,`pr_hour`,`spicality`,`city`,`online`,`intro`, (SQRT(POW((lat - $lat), 2) + POW((lang - $lang), 2)) * $multiplier) AS distance FROM users WHERE POW((lat - $lat), 2) + POW((lang - $lang), 2) < POW(($distance/$multiplier), 2) ORDER BY distance"; 
+1

MySQLまたはSQL Server? – Sami

+0

ごめんなさいMySQLのクエリ – user3676648

答えて

1

秒1でのサブクエリとして最初のものを使用します。

$query = " 
SELECT 
     `user_id`,`name`,`email`,`degree`,`avatar`,`mobile` 
     ,`sex`,`nationality`,`nationalitycode`,`birthday_year`,`pr_hour` 
     ,`spicality`,`city`,`online` 
     ,`intro` 
     , (SQRT(POW((lat - $lat), 2) + POW((lang - $lang), 2)) * $multiplier) AS distance 
     , r.`avg_rating` 
FROM users 
INNER JOIN (
     select 
      raiting.rated_user 
      ,avg(raiting.rate) as `avg_rating` 
     from raiting 
     group by raiting.rated_user 
    ) AS r on users.user_id = raiting.rated_user 
WHERE POW((lat - $lat), 2) + POW((lang - $lang), 2) < POW(($distance/$multiplier), 2) 
ORDER BY distance 
"; 

SQLクエリが複数の行に広がることができ 、それが道に簡単な予防措置をとる

を維持することを可能にしますSQLインジェクションを避けるために

0

これでも試すことができます:

$query = "SELECT `user_id`,`name`,`email`,`degree`,`avatar`, `mobile`,`sex`,`nationality`, `nationalitycode`,`birthday_year`,`pr_hour`, 
`spicality`,`city`,`online`,`intro`,t1.rated_user,t1.avg_rating 
(SQRT(POW((lat - $lat), 2) + POW((lang - $lang), 2)) * $multiplier) AS distance 
FROM users inner join (select raiting.rated_user,avg(raiting.rate) as `avg_rating` from raiting 
group by raiting.rated_user 
order by avg(raiting.rate) desc) t1 on users.user_id = t1.rated_user 
WHERE POW((lat - $lat), 2) + POW((lang - $lang), 2) < POW(($distance/$multiplier), 2) 
ORDER BY distance"; 
関連する問題