我无法围绕如何构建这个SQL查询。
我有3张桌子。
用户表
tag_ref 表
地理位置表
我需要做的是根据位置找到用户以及他们与之关联的标签。我有两个查询分开工作。
这是我用于位置查询的内容:
$sql_search_people = "SELECT user_id, ( 3959 * acos( cos( radians(?) ) * cos( radians( geolat ) ) * cos( radians( geolon ) - radians(?) ) + sin( radians(?) ) * sin( radians( geolat ) ) ) ) AS distance FROM geolocation
HAVING distance < '25'";
然后我需要通过tag_ref从tag_ref表中过滤结果。用户可以搜索多个标签。我在这里做了这个seperatley:
$sql_search_people = "SELECT b.user_id, b.name, b.picture, b.tagline, b.genres FROM tag_ref AS a LEFT JOIN users AS b ON a.user_id = b.user_id WHERE a.tag_id IN ($in) GROUP BY a.user_id";
现在我只需要弄清楚如何将两者结合成一个查询。哪个我搞不清楚!我已经尝试过加入和子查询,但我真的很难理解这些。
非常感谢任何帮助。
**更新**
在玩了一些之后我设法让这个工作:
$sql_search_people = "SELECT a.user_id, b.user_id, c.user_id, c.tag_id, b.name, ( 3959 * acos( cos( radians(?) ) * cos( radians( geolat ) ) * cos( radians( geolon ) - radians(?) ) + sin( radians(?) ) * sin( radians( geolat ) ) ) ) AS distance FROM geolocation AS a RIGHT JOIN tag_ref AS c ON a.user_id = c.user_id RIGHT JOIN users AS b ON a.user_id = b.user_id WHERE c.tag_id IN ($in) HAVING distance < '25' ";
但当然,它会复制用户拥有多个标记的结果。当我通过user_id将group by group添加到group时,查询失败了吗?
答案 0 :(得分:0)
我有一个想法,使用第一个查询是一个临时表来调用第二个查询:
SELECT b.user_id, b.name, b.picture, b.tagline, b.genres FROM tag_ref AS a LEFT JOIN users AS b ON a.user_id = b.user_id, (SELECT user_id, ( 3959 * acos( cos( radians(?) ) * cos( radians( geolat ) ) * cos( radians( geolon ) - radians(?) ) + sin( radians(?) ) * sin( radians( geolat ) ) ) ) AS distance FROM geolocation
HAVING distance < '25') as location WHERE a.tag_id IN ($in) GROUP BY a.user_id