简体   繁体   English

mysql选择条件是否存在

[英]mysql select distinct if condition exists

I have this table : 我有这张桌子:

std_id  std_type  std_dept  target
  1      type-1     ALL       15
  2      type-1     HRD       10
  3      type-2     ALL       1
  4      type-2     ACCTG     5
  5      type-3     ALL       5
  6      type-4     ALL       25
  1. std_dept with value ALL means std_target for each std_type are valid for all dept std_dept值为ALL手段std_target每个std_type适用于所有部门

  2. std_dept with specific dept value, override the value form point (1). 具有特定dept值的std_dept ,覆盖从点(1)开始的值。

So, my problem is lets say I am from HRD dept and I want to have the result set as follow: 因此,我的问题是可以说我来自HRD部门,我希望将结果设置如下:

std_id  std_type  std_dept  target
  2      type-1     HRD       10
  3      type-2     ALL       1
  5      type-3     ALL       5
  6      type-4     ALL       25

I really like to show my work, but I've got no clue at all, I don't know how to distinctly select * from std_table (for each std_type) where std_dept='HRD' if exist else get from std_dept='ALL' . 我真的很想展示我的作品,但是我一点都不知道,我不知道如何select * from std_table (for each std_type) where std_dept='HRD' if exist else get from std_dept='ALL'分别select * from std_table (for each std_type) where std_dept='HRD' if exist else get from std_dept='ALL'

I need pointers if not the code 我需要的指针,如果不是代码

You could use NOT EXISTS and correlated subquery: 您可以使用NOT EXISTS和相关子查询:

SELECT *
FROM tab
WHERE std_dept = 'HRD'           
UNION ALL
SELECT *
FROM tab t1
WHERE std_dept = 'ALL'
  AND NOT EXISTS (SELECT *
                  FROM tab t2
                  WHERE t2.std_dept = 'HRD'   
                    AND t1.std_type = t2.std_type);

DBFiddle Demo DBFiddle演示

It sounds like you want to weight it, so if you're from HRD then you want HRD or ALL, and if you want ACCTG then you want ACCTG or ALL, for types 1-4. 听起来好像要加权,所以如果您来自HRD,则要HRD或ALL,如果要ACCTG,则要ACCTG或ALL(对于类型1-4)。

You could group by std_type to make them distinct, and order by that to make the order correct. 您可以按std_type分组以使其区分,并按该顺序进行排序以使顺序正确。 For the weighting thing, you could create a column which is the result of a comparison against the same value you're using in your WHERE clause, eg something like: 对于加权,您可以创建一个列,该列是与您在WHERE子句中使用的相同值进行比较的结果,例如:

SELECT std_id, DISTINCT(std_type) AS std_type,
       std_dept, target, 
       IF (std_dept = 'HRD', 50, 10) AS weight
FROM mytable
WHERE std_dept IN ('ALL', 'HRD')
GROUP BY std_id, std_dept, target, weight
ORDER BY std_type

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

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