我想选择value1
,value2
其中item
= foo
IF返回的是一条不同的记录,否则我想返回所有{{1} } year
= item
的列,因此用户每年都可以看到foo
。
value
这就是我目前选择不同列的方式,但正如您可以通过我的问题所说,这个查询对于我需要做的事情来说并不复杂。
Item year value1 value2
-----------------------
foo 12 32 48
foo 13 32 50
foo 14 32 50
foo 15 33 48
foo 16 33 48
foo 17 33 48
fo3 13 38 42
fo3 14 34 44
fo4 15 36 46
fo5 16 37 48
根据当前表格,我想要的结果是SELECT distinct value1, value2
FROM MyTable
WHERE item = 'foo'
year
= item
的结果,因为有超过1个不同的结果。
例如:foo
然而,如果我的表格如下所示,12 13 14 15 16 17
= value1
只有value2
item
只有foo
value1
我只想value2
} Item year value1 value2
-----------------------
foo 12 32 50
foo 13 32 50
foo 14 32 50
foo 15 32 50
foo 16 32 50
foo 17 32 50
fo3 13 38 42
fo3 14 34 44
fo4 15 36 46
fo5 16 37 48
返回了
32 50
期望的结果
SELECT value1, value2
FROM MyTable
WHERE item = 'foo'
GROUP BY value1, value2 IF count = 1 ELSE
SELECT year From MyTable WHERE item = 'foo';
示例逻辑(不会按原样运行)
{{1}}
答案 0 :(得分:0)
试试:
SELECT year,value1, value2
FROM MyTable
WHERE item = 'foo'
GROUP BY value1, value2
编辑:
SELECT year,value1, value2, count(*)
FROM MyTable
WHERE item = 'foo'
GROUP BY value1, value2
HAVING count(*)=1
答案 1 :(得分:0)
您可以通过使用准备好的声明来实现这一目标:
SET @item = 'foo'; -- set to 'fo3' for a proof of the expected behaviour
SELECT COUNT(DISTINCT value1, value2)
INTO @count
FROM MyTable
WHERE item = @item;
SET @query = CONCAT('SELECT DISTINCT ', IF(@count = 1, 'value1, value2', 'year'),
' FROM MyTable WHERE item = \'', @item, '\'');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEMO @ SQL Fiddle
答案 2 :(得分:-1)
SELECT' count_one' as rec_cnt,year,value1,value2,count()FROM MyTable WHERE item =' foo' GROUP BY value1,value2 HAVING count()= 1
联盟
SELECT' count_many' as rec_cnt,year,value1,value2,count()FROM MyTable WHERE item =' foo' GROUP BY value1,value2 HAVING count()> 1