我有以下MySQL数据库:
variable displayname clevs ccols cmin cmax show_on_quicklinks client
'capesfc' 'cape' '100 200' '18 19' '100' '3400' 'gfs,access-c' NULL
'lftxsfc' 'li' '-10 -9' '50 52' '-10' '0' 'gfs' NULL
'lftxsfc' 'li' '-10 -9' '50 52' '-10' '0' 'gfs,access-c' 'client1'
'tscreen' 'tempsfc' '-10 45' '50 52' '-10' '45' 'gfs,access-c' 'client1'
'lftxsfc' 'li' '-10 -9' '50 52' '-10' '0' 'access-c' 'client2'
'capesfc1' 'cape1' '100 200' '18 19' '100' '3400' 'gfs,access-c' NULL
我想在client不为空的情况下选择唯一的displayname,否则只需返回displayname ...,因此在下面的示例中,如果我选择client ='client1',它将返回client1的行,并且还必须返回所有其他行客户为NULL的行。它不能为其他客户端返回任何其他行:
variable displayname clevs ccols cmin cmax show_on_quicklinks client
'lftxsfc' 'li' '-10 -9' '50 52' '-10' '0' 'gfs,access-c' 'client1'
'tscreen' 'tempsfc' '-10 45' '50 52' '-10' '45' 'gfs,access-c' 'client1'
'capesfc' 'cape' '100 200' '18 19' '100' '3400' 'gfs,access-c' NULL
'capesfc1' 'cape1' '100 200' '18 19' '100' '3400' 'gfs,access-c' NULL
答案 0 :(得分:0)
您可以尝试使用聚合进行以下操作,但是如果使用mysql的升级版,则可以使用row_number()函数,该函数最好容易地识别重复项
select variable,displayname,clevs,ccols,cmin,cmax,max(show_on_quicklinks) as show_on_quicklinks,max(client) as client
from tablename
gruop by variable,displayname,clevs,ccols,cmin,cmax
答案 1 :(得分:0)
更改样本后的修订查询:
set @client := 'client1';
set @var := (select variable from variables_info where client = @client limit 1);
SELECT
variable,displayname,clevs,ccols,cmin,cmax,show_on_quicklinks,client
FROM (
SELECT
@row_num :=IF(@prev_value = concat(v.variable, coalesce(v.client,'')), @row_num + 1, 1)AS RowNumber
, v.*
, @prev_value := concat(v.variable, coalesce(v.client,''))
FROM variables_info AS v
CROSS JOIN (SELECT @row_num :=1, @prev_value :='') vars
ORDER BY
v.variable, v.client
) AS d
WHERE (
(RowNumber = 1 and client = @client)
OR (RowNumber = 1 and client IS NULL and variable <> @var)
)
另请参阅:http://rextester.com/VHNDH48312
nb:上面的查询模拟了“ row_number()”,这是最近在MySQL 8和许多其他SQL投诉数据库中发现的非常有用的“窗口函数”。
原始:
这不是一个有效的查询,但是会从3个样本中找到所需的2行。
select
*
from variables_info
where (variable in (select variable from variables_info where client = 'client1') and client is not null
OR
variable NOT in (select variable from variables_info where client = 'client1') and client is null
)
请参阅::http://rextester.com/TAYM62841
如果您使用的是MySQL的最新版本,则可以使用更好的方法。
答案 2 :(得分:0)
这是您在rextester.com/UIJK63292上查询的一种变体
SELECT
a_index
,client
,variable
,displayname
,color_info
,clevs
,ccols
,cmin
,cmax
,cint
,show_on_models_quicklinks
FROM `variables_info`
WHERE `client` = 'client1'
OR (`client` IS NULL
and `displayname` IN (SELECT `displayname` FROM `variables_info`
WHERE `client` IS NULL
and NOT `displayname` IN (SELECT `displayname`
FROM `variables_info`
WHERE `client` = 'client1')
)
)
;
nb:我正在猜测您只希望此返回的client1尚未覆盖的任何显示名:
SELECT `displayname` FROM `variables_info`
WHERE `client` IS NULL
and NOT `displayname` IN (SELECT `displayname`
FROM `variables_info`
WHERE `client` = 'client1')