Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

complicated mysql query issue

Tags:

mysql

i want to show in my dashboard the top 5 product, on each product i want to show the total of order, views and the percentage of where that product is based on others ex:

Game 1 for Xbox (200 orders / 1000 views) 20%
Game 2 for WII (180 orders / 2100 views) 18%
Game 3 for PS3 (170 orders / 390 views) 17%
Game 4 for PS3 (90 orders / 1400 views) 9%
Game 5 for WII (20 orders / 30 views) 2%

so 200 orders for game 1 out of 1000 orders is 20% of total orders. which means, 20% of my products were game 1

here's my query:

select
 products.name, products.type, products.views, count(*) as orders, ????????
from
 products
inner join orders on (products.id = orders.product_id)
group by orders.product_id

how do i get the percentage?

like image 313
fred Avatar asked Dec 18 '11 18:12

fred


People also ask

Can MySQL perform complex queries?

What is a complex MySQL query? Complex MySQL queries search data using more than one parameter and may comprise a combination of several joins across multiple tables and quite a few nested subqueries (queries nested within another query). Complex queries also frequently involve heavy use of AND and OR clauses.

What are complex queries?

Complex queries help to narrow a detailed listing obtained as output from an API. To generate the desired output, you can pass queries using And or Or operators in the input XML of an API.

Why is my MySQL query running slow?

Queries can become slow for various reasons ranging from improper index usage to bugs in the storage engine itself. However, in most cases, queries become slow because developers or MySQL database administrators neglect to monitor them and keep an eye on their performance.

Which query will take more time for execution?

There are a number of things that may cause a query to take longer time to execute: Inefficient query – Use non-indexed columns while lookup or joining, thus MySQL takes longer time to match the condition. Table lock – The table is locked, by global lock or explicit table lock when the query is trying to access it.


1 Answers

select
 products.name, products.type, count(*) as orders, count(*) * 100 / total.total as pct
from
 products
inner join orders on (products.id = orders.product_id)
inner join (select count(*) as total from orders) total
group by orders.product_id
like image 166
necromancer Avatar answered Oct 27 '22 12:10

necromancer