简体   繁体   中英

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.

I have tried some queries but im having some trouble on how to join tables and how to use where clause

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

Rating by product and user 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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