Mysql SQL:选择重复值的第一行
从以下代码:Mysql SQL:选择重复值的第一行,mysql,sql,Mysql,Sql,从以下代码: SELECT farm_products.id as ID, farm_products.product as Product1, shop_products.product as Product2 FROM farm_products, shop_products, shop_farm WHERE farm_products.id = shop_farm.farm_id and shop_farm.farm_id = shop_products.id and
SELECT
farm_products.id as ID,
farm_products.product as Product1,
shop_products.product as Product2
FROM
farm_products,
shop_products,
shop_farm
WHERE
farm_products.id = shop_farm.farm_id and
shop_farm.farm_id = shop_products.id and
farm_products.product != shop_products.product;
我得到以下输出:
+-------+----------+---------+
|ID | Product1 | Product2|
+-------+----------+---------+
|06 | 'Apple' | 'Grape' |
+-------+----------+---------+
|06 | 'Orange' | 'Grape' |
+-------+----------+---------+
|06 | 'Pear' | 'Apple' |
+-------+----------+---------+
|07 | 'Apple' | 'Pear' |
+-------+----------+---------+
|08 | 'Kiwi' | 'Grape' |
+-------+----------+---------+
|08 | 'Grape' | 'Orange |
+-------+----------+---------+
我想要一张表,每个表中只出现第一行
ID出现
换句话说,我想要一个如下所示的输出:
+-------+----------+---------+
|ID | Product1 | Product2|
+-------+----------+---------+
|06 | 'Apple' | 'Grape' |
+-------+----------+---------+
|07 | 'Apple' | 'Pear' |
+-------+----------+---------+
|08 | 'Kiwi' | 'Grape' |
+-------+----------+---------+
我曾尝试使用DISTINCT删除所有重复的ID,但这显然不起作用。
我希望尽量避免嵌套查询,并使代码尽可能简单
有人能帮忙吗?使用排号
您可以按照下面的方式使用您的查询
with cte as
(
SELECT
farm_products.id as ID,
farm_products.product as Product1,
shop_products.product as Product2,
row_number() over(partition by farm_products.id order by
farm_products.product) rn
FROM
farm_products join
shop_products on farm_products.product != shop_products.product
join shop_farm on shop_farm.farm_id = shop_products.id
and farm_products.id = shop_farm.farm_id
) select * from cte where rn=1
这将有助于:
select * from (SELECT
farm_products.id as ID,
farm_products.product as Product1,
shop_products.product as Product2,
row_number() over(partition by farm_products.id order by
farm_products.id) rank
FROM
farm_products,
shop_products,
shop_farm
WHERE
farm_products.id = shop_farm.farm_id and
shop_farm.farm_id = shop_products.id and
farm_products.product != shop_products.product)
where rank=1
;
今天的提示:切换到现代的显式连接语法。更容易编写而不出错,更容易阅读和维护,并且在需要时更容易转换为外部联接。mysql版本?@Zaynulabadinuthin我相信我使用的是mysql 8.0.13.0您编写的第一个表是什么?输入输出您在查询中提到的表代表哪些表?什么决定了第一行?无法保证数据按表顺序排列,那么该如何对这些数据进行排序?为什么id 06的第1行是apple而不是橙色?@nikhilsugandh mysql 8+版本支持窗口函数
select * from (SELECT
farm_products.id as ID,
farm_products.product as Product1,
shop_products.product as Product2,
row_number() over(partition by farm_products.id order by
farm_products.id) rank
FROM
farm_products,
shop_products,
shop_farm
WHERE
farm_products.id = shop_farm.farm_id and
shop_farm.farm_id = shop_products.id and
farm_products.product != shop_products.product)
where rank=1
;