简体   繁体   English

mysql 查询结果获取同一id上的一条记录

[英]mysql query result to get one record on same id

Hi looking to see how would i write the mysql statement that result in one record if there have same id.嗨,我想看看我将如何编写 mysql 语句,如果有相同的 id 会产生一条记录。

I have two tables order_userinfos and orders, here my join statement我有两个表 order_userinfos 和 orders,这里是我的 join 语句

SELECT *
  FROM col_order_userinfos i
  JOIN col_orders o
    ON i.col_order_id = o.order_number
 WHERE o.order_number > 226690

The results came out like this结果是这样出来的

col_order_userinfo_id   virtuemart_order_id virtuemart_user_id  address_type
   51548                 226691                2611                BT
   51549                 226691                2611                ST
   51550                 226692                2611                BT
   51551                 226692                2611                ST
   51552                 226693                2611                BT
   51553                 226693                2611                ST
   51554                 226694                2611                BT

As you can see, I get same order_id result twice with the address_type either 'ST' OR 'BT' also, I have one order_id that have one order_id and address_type 'BT'.如您所见,我得到相同的 order_id 结果两次,address_type 为“ST”或“BT”,我有一个 order_id,其中一个 order_id 和 address_type 为“BT”。

Here the result i am looking for这是我正在寻找的结果

col_order_userinfo_id   virtuemart_order_id virtuemart_user_id  address_type
     51549               226691                2611                ST
     51551               226692                2611                ST
     51553               226693                2611                ST
     51554               226694                2611                BT

I tried with group by order_id in my query, the results will only show up with address_type 'BT'.我在查询中尝试使用 group by order_id,结果只会显示 address_type 'BT'。 What would be the best way to write mysql statement that get my desire result?编写 mysql 语句以获得我想要的结果的最佳方法是什么?

I believe you can use ROW_NUMBER() function like我相信您可以使用ROW_NUMBER() function 之类的

SELECT col_order_userinfo_id,
      virtuemart_order_id,
      virtuemart_user_id,
      address_type
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY i.col_order_userinfo_id 
                         ORDER BY i.col_order_userinfo_id DESC) AS row_num
  FROM col_order_userinfos i
  JOIN col_orders o
    ON i.col_order_id = o.order_number
 WHERE o.order_number > 226690 ) xx
WHERE row_num = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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