简体   繁体   English

使用联接的MySQL查询搜索

[英]MySQL query search using joins

I have the following tables: 我有以下表格:

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)

How can I select (search) products and rating (average) by Category (name or id) and order them by Title or by rating. 如何选择按类别(名称或ID)选择(搜索)产品和等级(平均),并按标题或等级排序。

I have tried some queries but im having some trouble on how to join tables and how to use where clause 我已经尝试了一些查询,但是即时通讯在如何联接表以及如何使用where子句方面遇到了一些麻烦

Do you mean something like that? 你的意思是那样吗?

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
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;

Method 1 方法1

Rating by product and user id 按产品和用户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

Refer http://sqlfiddle.com/#!9/014af/6 请参阅http://sqlfiddle.com/#!9/014af/6

Method 2 方法二

Rating by product id 按产品编号评分

Different users will rate the same product, so we have to consider the average rating of each product. 不同的用户会对同一产品进行评分,因此我们必须考虑每种产品的平均评分。

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

Refer http://sqlfiddle.com/#!9/014af/7 请参阅http://sqlfiddle.com/#!9/014af/7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM