P粉4810352322023-08-29 16:08:14
First, let me correct you; that's not a Navicat query, that's a MySQL query. Now, these are two different things. MySQL is a database, Navicat is a tool - similar to other tools like MySQL Workbench, PHPMyAdmin or SQLyog. It is designed to allow you to perform database functions through a graphical interface.
Next, I will give two queries, you can use one of them depending on your MySQL version. The first query is as follows:
SELECT p1.idproduct, p1.exp_date, p1.selling_price FROM product_exp_date p1 JOIN ( SELECT idproduct, MIN(exp_date) AS minexp FROM product_exp_date GROUP BY idproduct ) AS p2 ON p1.idproduct=p2.idproduct AND p1.exp_date=p2.minexp ORDER BY p1.idproduct;
You should be able to run the above query in any version of MySQL or MariaDB. The idea of this query is to obtain the smallest exp_date
by idproduct
grouping, and then use it as a subquery to connect with the product
table again to match these two Extracted value so that we can extract selling_price
.
Second query:
SELECT idproduct, exp_date, selling_price FROM ( SELECT idproduct, exp_date, selling_price, ROW_NUMBER() OVER (PARTITION BY idproduct ORDER BY exp_date) rn FROM product_exp_date ) AS p1 WHERE rn=1;
This query can only be run on MySQL v8 or MariaDB 10.2 (and above) that supports window functions. The idea is a bit different compared to the previous query, here we will focus on generating ROW_NUMBER()
based on specific conditions, then make it a subquery and only add a WHERE
clause . Compared to the previous query, this requires no JOIN
operation.
You can see that I didn't take into account the product
table because I didn't see it being used in your original query, but if you do need to join it and you can't get Know how to do it, just drop me a message and I'll see what I can do.