MySQL:子查询:警告消息含义

时间:2016-04-12 22:17:54

标签: mysql sql subquery warnings

我写了一个查询来报告将于2016年到期的信用卡。它运行,但我确实收到警告,我想知道更多有关原因的信息。我认为这是因为子查询。

  

警告:数据值不正确:第1行第'exp_date'列的'2016%'

我只有一个符合2016年要求的价值,但由于未来可能出现的价值可能会达到相同的条件而出现警告吗?

SELECT customer_id as 'Customer'
FROM customers
WHERE credit_card_id = (
        SELECT credit_card_id
        FROM credit_cards
        WHERE exp_date LIKE '2016%'
        LIMIT 1
    );

信用卡价值:

INSERT INTO credit_cards VALUES 
(1, '0025184796520000', '2016-08-13', 'Sarah', 'Jones', 3351, '2490 Paseo Verde parkway, suite 150', 'San Diego','CA',92124),
(2, '7896541232548526', '2017-09-21', 'Desmond', 'Lowell', 1204, '3201 Kelsey Street, suite 109', 'San Diego','CA',92174),
(3, '1234567890123456', '2018-02-11', 'Mark', 'Jefferson', 1591, '876 Silverado Street, suite 304', 'Henderson','NV',89162),
(4, '4001330852539605', '2017-01-10', 'Jaime', 'Evans', 8879, '924 Shady Pines Circle, suite 120', 'Summerlin','NV',89074);

1 个答案:

答案 0 :(得分:1)

问题在于数据类型DATE<> TEXT以及'2016%' to DATE`的隐式转换,必须失败。

您可以使用(不是SARGable):

SELECT customer_id as 'Customer'
FROM customers
WHERE credit_card_id = (
        SELECT credit_card_id
        FROM credit_cards
        WHERE YEAR(exp_date) =  2016
    );

第二项改进是使用JOIN

SELECT DISTINCT c.customer_id AS `Customer`
FROM customers c
JOIN credit_cards cc
  ON cc.credit_card_id = c.credit_card_id
WHERE YEAR(cc.exp_date) = 2016;

最后,你可以使用SARGable

WHERE cc.exp_date >= '2016-01-01' AND cc.exp_date < '2017-01-01'