The rewritten title is: Get the products purchased by the first 10 customers
P粉386318086
2023-08-29 21:31:29
<p>I want to write a SQL query in laravel/php to get the top 10 different products purchased by customers. </p>
<p>My table structure is as follows:</p>
<ul>
<li><code>Orders</code>Table (Customer ID, Product ID, etc...)</li>
<li><code>Products</code>Table (product ID, product name, etc...)</li>
</ul>
<p>This is my query attempt: </p>
<pre class="brush:php;toolbar:false;">SELECT products.*
FROM products
WHERE products.id = [SELECT DISTINCT (products.id)
FROM orders
WHERE customer.id=id->list(10)]</pre></p>
I can see the direction you're trying to go with your query, but unfortunately that won't give you the top 10 results. Instead, you might get no results at all:
=
means you are looking for an exact match and your subquery should return 10 rows of data. If you use this operation, you will receive this error.But if you change it to
IN
, you may get this errorBased on your current attempt, your option is to perform a
JOIN
. However, I was wondering how you got your top 10? I can see you are looking for a product in the top 10, but based on what? Sales Amount? Order quantity?In this sense, here is an example of the top 10 products sorted by order quantity.
The subquery is not necessary, but I am imitating the subquery you tried, although the process is not exactly the same. Here's the version without the subquery:
Or maybe you are looking for the top 10 sorted by sales amount?
Demo fiddle