I am making a website where users add the place where they have visited.
There is 4 main tables
users (user_id,name )
places (place_id,type_id,place_name, city_id)
user_place (user_id,place_id, date )
city(city_id,city_name)
Now I need to take with one query all the places which are type of 2 (where type=2)
where the given users participate (user_id=43 lets say)
with the name of the place, name of the city and the quantity of ALL OTHER users which are also participating in the same place...
Yesterday with one book about mysql I came to such thing
SELECT *
FROM `user_place` , `places`,(SELECT count(user_id)
from user_places
WHERE user_place.place_id = places.place_id) as count
WHERE user_place.place_id = places.place_id
AND user_place.user_id =53
But its giving error:Unknown column 'places.place_id' in 'where clause' And still no Idea how can I also attach smartly the p开发者_StackOverflow中文版lace name and city name to the result... Please help if you can...
You can look at something like this
SELECT u.user_id,
u.NAME,
p.place_id,
p.place_name,
c.city_id,
c.city_name,
placeCount.Cnt
FROM places p INNER JOIN
user_place up ON p.place_id = up.place_id INNER JOIN
users u ON up.user_id = u.user_id INNER JOIN
city c ON p.city_id = c.city_id LEFT JOIN
(
SELECT place_id,
COUNT(DISTINCT user_id) Cnt
FROM user_place
WHERE user_id <> 43
GROUP BY place_id
) placeCount ON p.place_id = placeCount.place_id
WHERE p.type_id = 2
AND up.user_id = 43
SELECT p.place_id, p.place_name, c.city, placeCount.Cnt
FROM places p
INNER JOIN user_place up ON p.place_id = up.place_id
INNER JOIN fa_user u ON up.user_id = u.id
INNER JOIN city c ON p.city_id = c.id
LEFT JOIN (
SELECT place_id, COUNT( DISTINCT user_id ) Cnt
FROM user_place
WHERE user_id <>53
GROUP BY place_id
)placeCount ON p.place_id = placeCount.place_id
WHERE up.user_id =53
LIMIT 0 , 30
精彩评论