使用连接进行MySQL查询搜索

时间:2016-06-12 12:32:30

标签: php mysql select join sql-order-by

我有以下表格:

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子句

方面遇到了一些麻烦

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

答案 2 :(得分: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