【问题标题】:How to change value of a column if the column does not have specific text?如果列没有特定文本,如何更改列的值?
【发布时间】:2018-08-02 01:33:37
【问题描述】:

我有一张这样的桌子:

+---------+-------+
| Fruits  | Price |
+---------+-------+
| Apple   | 2.00  |
| Orange  | 3.00  |
| Banana  | 4.00  |
+---------+-------+

如果Fruits 列没有Grapes 那么 如何返回 0 的价格 喜欢

+---------+-------+
| Fruits  | Price |
+---------+-------+
| Grape   | 0.00  |
+---------+-------+

这是我的查询

Select
    Fruits, 
    Price
From
    Products

【问题讨论】:

  • 您应该在此表中添加所有水果并为其添加默认值,因为数据库无法神奇地插入一行。如果某些列不包含值,它可以为某些列添加默认值,但如果没有行,则无法识别,而不是添加查询(这会使查询变得复杂),您应该将它们添加到表中。

标签: mysql sql mysql-workbench


【解决方案1】:

理想情况下,您应该有一个表格,其中包含您希望出现在报告中的所有水果的名称。所以,这样的事情应该可以工作:

SELECT
    p.Fruits,
    COALESCE(p.Price, 0.00) AS Price
FROM
(
    SELECT 'Apple' AS Fruits UNION ALL
    SELECT 'Orange' UNION ALL
    SELECT 'Banana' UNION ALL
    SELECT 'Grape'
) AS all_fruits
LEFT JOIN Products p
    ON all_fruits.Fruits = p.Fruits;

如果您只想查看不匹配的水果,则可以在查询末尾添加以下内容:

WHERE p.Fruits IS NULL

【讨论】:

    【解决方案2】:

    你可以这样做:

    select x.*
    from (select 'Grapes' as fruit, 0.00 as price) x
    where not exists (select 1 from atable t where t.fruit = 'Grapes');
    

    【讨论】:

      【解决方案3】:

      这也是使用NOT IN 执行相同Select from the same table 的另一种方法,如果表中有多行,它将返回重复值,因此我们可以在MYSQL 中使用DISTINCTLIMIT

      SELECT DISTINCT 'Grapes' AS fruit, 
          0.00 AS price
      FROM yourTable
      WHERE 'Grapes' NOT IN (fruits)
      

      注意:如果表为空白,它不会返回任何记录,我希望在这种情况下返回值也没有意义,但如果你仍然想返回一个,那么我必须说对不起:) 在这种情况下.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-08
        • 1970-01-01
        • 1970-01-01
        • 2022-08-16
        • 1970-01-01
        • 1970-01-01
        • 2016-11-03
        • 1970-01-01
        相关资源
        最近更新 更多