2017-07-28 61 views
-1

我有我的分贝Mysql的三重加入错误:没有唯一的表/别名: 'cushbu_mark_user_favorites'

1)3个表cushbu_users (id,first_name,last_name)

2)cushbu_art (id,user_id(FK cushbu_user),title,base_price etc...) - 用于存储用户的艺术

3)cushbu_mark_user_favorites (id,user_id(FK cushbu_user),art_id(FK cushbu_art)) - 用于标记心仪的物品

我想获取特定用户的所有的艺术项目收藏最多
随着收藏数量各领域(存储在cushbu_mark_usier_favorites表)

这里是我的查询

SELECT 
    cushbu_art.id AS art_id, 
    cushbu_art.title, 
    cushbu_art.base_price, 
    cushbu_art.image_name, 
    CONCAT(
     cushbu_users.first_name, 
     ' ', 
     cushbu_users.last_name 
    ) AS artist_name,COUNT(cushbu_mark_user_favorites.art_id) 
FROM 
    cushbu_art 
JOIN cushbu_mark_user_favorites ON cushbu_mark_user_favorites.art_id = cushbu_art.id 
JOIN cushbu_users ON cushbu_users.id = cushbu_art.artist_id 
LEFT JOIN cushbu_mark_user_favorites ON cushbu_art.id=cushbu_mark_user_favorites.art_id 
WHERE 
    cushbu_mark_user_favorites.user_id = 68 

但我得到Not unique table/alias: 'cushbu_mark_user_favorites'join声明

LEFT JOIN cushbu_mark_user_favorites ON cushbu_art.id=cushbu_mark_user_favorites.art_id 

UPDATE

SELECT 
    a.id AS art_id, 
    a.title, 
    a.base_price, 
    a.image_name, 
    CONCAT(
     c.first_name, 
     ' ', 
     c.last_name 
    ) AS artist_name,COUNT(b.art_id) 
FROM 
    cushbu_art a 
JOIN cushbu_mark_user_favorites b ON b.art_id = a.id 
JOIN cushbu_users c ON c.id = a.artist_id 
LEFT JOIN b ON a.id=b.art_id 
WHERE 
    b.user_id = 68 
+0

那么什么是不清楚......?由于您不止一次加入同一个表,因此您需要使用别名,以便在任何时候都不会含糊其中指出哪个实例... – CBroe

+0

@chiragsatapara这里是解释的版本https:// stackoverflow .com/questions/45373911/mysql-joinget-total-favorites-for-each-item-along-with-each-row – Jabaa

+0

当然我会接受它 – Jabaa

回答

0

请尝试以下查询。

SELECT 
    cushbu_art.id AS art_id, 
    cushbu_art.title, 
    cushbu_art.image_name, 
    CONCAT(
     cushbu_users.first_name, 
     ' ', 
     cushbu_users.last_name 
    ) AS artist_name , b.favorites_count as total_fav 
FROM 
    cushbu_mark_user_favorites 
LEFT JOIN cushbu_art ON cushbu_art.id=cushbu_mark_user_favorites.art_id 
LEFT JOIN cushbu_users ON cushbu_users.id = cushbu_art.artist_id 
LEFT JOIN (SELECT art_id,count(*) as favorites_count FROM cushbu_mark_user_favorites GROUP BY art_id) as b ON b.art_id=cushbu_art.id 
WHERE cushbu_mark_user_favorites.user_id=1 
GROUP BY cushbu_art.id 

希望这对你有帮助。

+0

错误'n聚合查询没有GROUP BY,SELECT列表的表达式#1包含非聚集列'cushbu_db.cushbu_art.id';这是不符合sql_mode = only_full_group_by' – Jabaa

+0

另一个错误'未知列'cushbu_mark_user_favorites.user_id''where子句'' – Jabaa

+0

没有错误,但我的结果是错误的总数是1 – Jabaa

相关问题