简体   繁体   中英

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.

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.

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.

2nd condition is to filter Shipping address types which do not have Billing with the same ID.

Result in SQL Fiddle

Try this -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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