简体   繁体   English

如果满足条件,则从结果中排除

[英]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 ? 有没有办法比较SELECT语句中的结果?

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 ? 这在MySQL中可能吗,还是创建一个Array并这样做更好?

Thanks, 谢谢,

Rick 里克

Edit for @Jim 编辑@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. Acme公司和Acme公司(西北)是同一家公司,因此,如果它们都出现在结果中(有时却不出现),则首选是只显示Acme公司的价格。

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 . 供应商根据case的条件查询此订单。 Because of the desc keyword, 'Supplier2' will be first and 'Supplier1' will be second. 由于使用了desc关键字,因此'Supplier2'将是第一个,而'Supplier1'将是第二个。 The limit chooses the first row which will be 'Supplier2' if present and otherwise 'Supplier1' . limit选择第一行'Supplier2'如果存在)将为'Supplier2' ,否则为'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. 即也许有一个parent_supplier字段。

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

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