SQL 查询 return table if exists retun price 2 else return price 1

SQL query to return table with if exists retun price 2 else return price 1

我需要帮助进行查询以显示以下结果。

假设我有表:

Table 1

ProductId   Description
1           Banana
2           Apple
3           Melon
4           Orange

Table 2

ProductId   PriceNumber   Price
1           1             86
1           2             55
2           1             58
3           1             99
3           3             66
4           1             87
4           2             78

我需要显示 PriceNumber = 2,如果不存在则显示 PriceNumber = 1

想要的结果:

ProductId   Description PriceNum    Price
1           Banana      2           55
2           Apple       1           58
3           Melon       1           99
4           Orange      2           78

谢谢!

表格设置如下:

CREATE TABLE Table1
    (`ProductId` int, `Description` varchar(6))
;

INSERT INTO Table1
    (`ProductId`, `Description`)
VALUES
    (1, 'Banana'),
    (2, 'Apple'),
    (3, 'Melon'),
    (4, 'Orange')
;


CREATE TABLE Table2
    (`ProductId` int, `PriceNumber` int, `Price` varchar(5))
;

INSERT INTO Table2
    (`ProductId`, `PriceNumber`, `Price`)
VALUES
    (1, 1, '7,86'),
    (1, 2, '3,55'), 
    (2, 1, '10,58'),
    (3, 1, '2,99'),
    (4, 1, '9,87'),
    (4, 2, '6,78')
;

代码中的实际答案如下:

SELECT  distinct(Table2.ProductId), 
        Description,
        PriceNumber, 
        Price 
FROM Table2
    INNER JOIN Table1
    ON Table1.ProductId = Table2.ProductId

WHERE (PriceNumber = 2) OR 
      (
          (Table2.ProductId not in (
                     SELECT ProductId 
                     FROM Table2 
                     WHERE PriceNumber = 2
                     )
           )
           AND
        (PriceNumber = 1)
       )

这是一个 link 的 sqlfiddle,您可以在其中玩代码: http://sqlfiddle.com/#!9/234ab/4/0