我正在处理此查询,但有些困难。联接对我来说很有意义,但是从images
表(其中有一个名为user_image
的联结表)中获取数据正在使我逃脱。
SELECT c.id, c.city, ROUND(( 3959 * acos( cos( radians(27.9861) ) * cos( radians( lat ) )
* cos( radians( lng ) - radians(-80.6628) ) + sin( radians(27.9861) ) * sin(radians(lat)) ) ),0) AS distance, t.id, t.name, t.price, t.duration, d.description, u.fname, i.image_path, i.image_name
FROM city c
JOIN trip t ON c.id = t.city_id
JOIN trip_description d ON t.id = d.trip_id
JOIN user u ON t.user_id = u.id
-- Need to get all images that match trip and is_main = 1
HAVING distance < 20
ORDER BY distance
LIMIT 0 , 45;
我的图像表看起来像这样...
不确定我是否应该在查询中使用另一个联接,联合,查询?真是茫然,不胜感激,将有所帮助:)
答案 0 :(得分:0)
假设您要查找给定用户的所有与is_main = 1
和is_active = 1
匹配的图像名称:
SELECT c.id as city_id, c.city, u.fname, t.name, d.description, i.image_name
FROM image i
LEFT JOIN user_image ui ON ui.image_id = i.id
LEFT JOIN user u ON u.id = ui.user_id
LEFT JOIN trip t ON t.id = ui.trip_id
LEFT JOIN trip_description d ON t.id = d.trip_id
LEFT JOIN city c ON c.id = t.city_id
WHERE u.id = 1
AND i.is_main = 1
AND i.active = 1
ORDER BY c.id;
答案 1 :(得分:0)
好吧,我想我明白了。感谢所有回应。
SELECT c.id, c.city, ROUND(( 3959 * acos( cos( radians(27.9861) ) * cos( radians( lat ) )
* cos( radians( lng ) - radians(-80.6628) ) + sin( radians(27.9861) ) * sin(radians(lat)) ) ),0) AS distance, t.id, t.name, t.price, t.duration, d.description, u.fname, i.path, i.name
FROM city c
JOIN trip t ON c.id = t.city_id
JOIN trip_description d ON t.id = d.trip_id
JOIN user u ON t.user_id = u.id
LEFT OUTER JOIN user_image ui ON ui.trip_id = t.id
LEFT OUTER JOIN image i ON ui.image_id = i.id
AND i.main=1
HAVING distance < 20
ORDER BY distance
LIMIT 0 , 45;