简体   繁体   English

MySQL根据where子句从具有相同字段的多个行中选择1个

[英]MySQL select 1 of multiple rows with same field based on where clause

I need to be able to select my entire table but where there are duplicate id's, only select 1 of them based on the data in a different field. 我需要能够选择我的整个表,但是在有重复ID的地方,只能根据不同字段中的数据选择其中之一。

For example if my table looks like this 例如,如果我的桌子看起来像这样

在此处输入图片说明

I want to select all rows, but if there are 2 of the same id, select only the row with Billing as the address type. 我想选择所有行,但是如果有2个相同的ID,请仅选择Billing作为地址类型的行。

You can do it this way: 您可以这样操作:

select * from Table1 
where (AddressType='Billing') or
(AddressType='Shipping' and ID not in (select ID from Table1 where AddressType='Billing'))
order by ID

Explanation: 说明:

1st condition is to filter only Billing address types. 第一个条件是仅过滤Billing地址类型。

2nd condition is to filter Shipping address types which do not have Billing with the same ID. 第二个条件是过滤不具有相同ID的Billing Shipping地址类型。

Result in SQL Fiddle SQL小提琴的结果

Try this - 尝试这个 -

SELECT *, ADDRESS
FROM (SELECT MIN(ID), ADDRESSTYPE
      FROM YOUR_TABLE
      GROUP BY ADDRESS) X

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

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