简体   繁体   中英

Exclude from results if condition is met

I have suppliers table with many different suppliers in it but I wanted to show one particular supplier rather than the other if they are both present. Is there a way to compare the results in a SELECT statement ?

Something along the lines of:

SELECT 
supplier,
price 
FROM table 
If IN supplier (Supplier1,Supplier2) Then 
SELECT supplier  
FROM table 
WHERE supplier <> Supplier1

Is this possible in MySQL or would it be better to create an Array and do it that way ?

Thanks,

Rick

Edit for @Jim

At the moment I'm selecting all and the results look like:

Supplier Name | Supplier Price
Acme Company | $12
Acme Company (Northwest)    | $12
Bobs Company    | $13
Craigs Company  | $15

Acme Company and Acme Company (Northwest) are the same company, so in the cases that they both appear in the results (they sometimes do not) then the preference is to have just Acme Companys price displayed.

If you only want one row returned, then you can do a fancy sort and select the first result:

SELECT supplier, price
FROM table 
WHERE supplier in (Supplier1, Supplier2)
ORDER BY (case when supplier = 'Supplier1' then 1
               when supplier = 'Supplier2' then 2
          end) DESC
LIMIT 1;

This query order by the suppliers, based on the conditions in the case . Because of the desc keyword, 'Supplier2' will be first and 'Supplier1' will be second. The limit chooses the first row which will be 'Supplier2' if present and otherwise 'Supplier1' .

EDIT:

If you just want to eliminate one supplier if another is present then do:

select supplier, price
from table t
where not (supplier = 'Supplier1' and
           exists (select 1 from table t2 where t2.supplier = 'Supplier2'
          );

This will return a list that has one supplier or the other, but not both.

You could group by the supplier field, switching it if the supplier is the sub company:

SELECT 
IF(supplier = 'Acme Company (Northwest)', 'Acme Company',supplier),
price 
FROM table
GROUP BY IF(supplier = 'Acme Company (Northwest)', 'Acme Company',supplier)

A nicer long term solution would be to store companies which are duplicates. Ie perhaps having a parent_supplier field.

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