mysql - select: result based on occurrence of explicit value -
given following mysql table:
create table fonts (`id` int, `fontname` varchar(22), `price` int,`reducedprice` int,`weight` int) ; insert fonts (`id`, `fontname`, `price`,`reducedprice`,`weight`) values (1, 'regular', 50,30,1), (2, 'regular-italic', 50,20,1), (3, 'medium', 60,30,2), (4, 'medium-italic', 50,30,2), (5, 'bold', 50,30,3), (6, 'bold-italic', 50,30,3), (7, 'bold-condensed', 50,30,3), (8, 'super', 50,30,4) ;
as example user chooses following ids: 1,2,3,5,6,7 result in following query/result:
> select * fonts id in(1,2,3,5,6,7); id fontname price reducedprice weight 1 regular 50 30 1 2 regular-italic 50 20 1 3 medium 60 30 2 5 bold 50 30 3 6 bold-italic 50 30 3 7 bold-condensed 50 30 3
is possible have kind of "if statement" in query return new field based on column weight. value occurs more once reducedprice should returned newprice else price:
id fontname price reducedprice weight newprice 1 regular 50 30 1 30 2 regular-italic 50 20 1 20 3 medium 60 30 2 60 5 bold 50 30 3 30 6 bold-italic 50 30 3 30 7 bold-condensed 50 30 3 30
which means ids 1,2,5,6,7 should reduced id 3 not weight "2" occurs once
please find fiddle here: http://sqlfiddle.com/#!9/73f5db/1 , help!
write subquery gets number of occurrences of each weight, , join this. can test number of occurrences decide field put in newprice
.
select f.*, if(weight_count = 1, price, reducedprice) newprice fonts f join (select weight, count(*) weight_count fonts id in (1, 2, 3, 5, 6, 7) group weight) w on f.weight = w.weight id in (1, 2, 3, 5, 6, 7)
Comments
Post a Comment