select:基于显式值的出现的结果

时间:2015-06-14 21:01:49

标签: mysql sql

鉴于以下是mysql表:

CREATE TABLE fonts
    (`id` int, `fontName` varchar(22), `price` int,`reducedPrice` int,`weight` int)
;

INSERT INTO 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)
;

作为示例,用户选择以下ID:1,2,3,5,6,7 这将导致以下查询/结果:

> select * from fonts where 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

是否可以在查询中使用一种“if语句”来返回基于列权重的新字段。如果值出现多次,则reducePrice应作为newPrice返回其他价格:

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

这意味着应该减少ID 1,2,5,6,7但是ID 3不是因为它的重量“2”只发生一次

请在此处找到一个小提琴:http://sqlfiddle.com/#!9/73f5db/1 谢谢你的帮助!

3 个答案:

答案 0 :(得分:1)

编写一个子查询,获取每个权重的出现次数,然后加入。然后,您可以测试出现次数,以决定将哪个字段放入NewPrice

SELECT f.*, IF(weight_count = 1, Price, ReducedPrice) AS NewPrice
FROM fonts AS f
JOIN (SELECT weight, COUNT(*) AS weight_count
      FROM fonts
      WHERE id IN (1, 2, 3, 5, 6, 7)
      GROUP BY weight) AS w ON f.weight = w.weight
WHERE id IN (1, 2, 3, 5, 6, 7)

Updated fiddle

答案 1 :(得分:0)

select *,if(occurences>=2,reducedPrice,price) as newPrice from fonts
left join (Select count(id) as occurences, id,weight from fonts
where fonts.id in(1,2,3,5,6,7) group by weight) t on t.weight = fonts.weight
where fonts.id in(1,2,3,5,6,7);

mysql if关键字引用在这里:https://dev.mysql.com/doc/refman/5.1/en/control-flow-functions.html#function_if

编辑:添加小提琴,根据请求更改为实例。 更新了小提琴:http://sqlfiddle.com/#!9/a93ef/14

答案 2 :(得分:0)

SELECT DISTINCT x.*
              , CASE WHEN y.weight = x.weight THEN x.reducedPrice ELSE x.price END newPrice 
           FROM fonts x 
           LEFT 
           JOIN 
              ( SELECT * FROM fonts WHERE id IN(1,2,3,5,6,7) )y
             ON y.weight = x.weight 
            AND y.id <> x.id  
          WHERE x.id IN(1,2,3,5,6,7)
          ORDER 
             BY id;