2016-06-12 186 views
0

我有以下表格:MySQL查詢搜索加入

products table 
------------- 
id 
name 
... 

categories table 
---------------- 
id 
name 

product_categories table 
------------------------ 
product_id 
category_id 

product_ratings 
--------------- 
product_id 
user_id 
rating (1 to 5 INT) 

我如何選擇(搜索)產品等級(平均)類別(名稱或ID),並責令其按標題或評級。

我已經試過有如何連接的表一定的麻煩,以及如何使用WHERE子句

回答

2

你的意思是這樣一些疑問,但即時通訊?

select 
    products.name, categories.name, product_ratings.rating 
from products 
join product_categories on products.id = product_categories.product_id 
join categories on categories.id = product_categories.category_id 
join product_ratings on product_ratings.product_id = products.id 
where 
    categories.name = 'CATEGORY NAME' 
order by 
    product_ratings.rating 
+0

謝謝!我有1個問題,雖然:如果沒有評級的產品它返回null(所有列),我怎麼能做到這一點,索托返回所有選定的列,但評級它有0例如? – user2493164

0
select p.name, r.rating 
from products as p 
inner join product_ratings as r on p.id = r.product_id 
inner join categories as c on c.id = pc.category_id 
inner join product_categories as pc = pc.product_id = p.id 
where c.name = 'search_name' 
order by r.rating; 
+0

您的意思是按順序ryrating ... – quantummind

+0

@quantummind謝謝 – scaisEdge

0

方法1

由產品和用戶ID等級

SELECT 
P.name, PR.user_id , IFNULL(PR.rating,0) as rating 
FROM products P 
JOIN product_categories PC ON P.id = PC.product_id 
JOIN categories C ON C.id = PC.category_id 
JOIN product_ratings PR ON PR.product_id = P.id 
WHERE C.name = 'Category A' 
ORDER BY P.name 

http://sqlfiddle.com/#!9/014af/6參見

方法2

評級由產品ID

不同的用戶會率相同的產品,所以我們要考慮的平均評價每一款產品。

SELECT 
P.name, GROUP_CONCAT(PR.user_id) as user_ids, AVG(IFNULL(PR.rating,0)) as rating 
FROM products P 
JOIN product_categories PC ON P.id = PC.product_id 
JOIN categories C ON C.id = PC.category_id 
JOIN product_ratings PR ON PR.product_id = P.id 
WHERE C.name = 'Category A' 
GROUP BY P.id 
ORDER BY P.name 

參考http://sqlfiddle.com/#!9/014af/7