在mysql请求中使用IF控制流

时间:2011-08-29 09:09:57

标签: mysql

我想根据mysql表中列的内容返回一个值。

示例:如果'newsletter'= 1则返回“订阅者”否则“未订阅”

我试过这种语法:

SELECT `id_customer`, `email`, `firstname`, `lastname`, `birthday`,
                    CASE WHEN `newsletter`=1 THEN "Abonné" ELSE "Non Abonné" END
                    FROM `"._DB_PREFIX_."customer`
                    ORDER BY `lastname` ASC

它绝对不起作用。

请帮助一点?

3 个答案:

答案 0 :(得分:1)

尝试使用

SELECT id_customer, email, firstname, lastname, birthday, 
IF(newsletter=1, "Abonné", "Non Abonné") is_subscribed 
FROM "._DB_PREFIX_."customer ORDER BY lastname ASC

答案 1 :(得分:1)

CREATE TABLE customer (
    id_customer INT(10),
    email VARCHAR(250),
    firstname VARCHAR(100),
    lastname VARCHAR(100),
    birthday DATE,
    newsletter TINYINT(1)
);

INSERT INTO customer (id_customer, email, firstname, lastname, birthday, newsletter)
VALUES (1, 'abe@example.com', 'Abe', 'Aaronson', '1965-12-31', 1),
    (2, 'bill@example.com', 'Bill', 'Bond', '1925-05-01', 0);

您的原始查询(我只是删除了反引号并用标准引号替换了ANSI引号,而不是因为它们错了):

SELECT id_customer, email, firstname, lastname, birthday,
CASE WHEN newsletter=1 THEN 'Abonné' ELSE 'Non Abonné' END
FROM customer
ORDER BY lastname ASC;

...打印:

+-------------+------------------+-----------+----------+------------+------------------------------------------------------------+
| id_customer | email            | firstname | lastname | birthday   | CASE WHEN newsletter=1 THEN 'Abonné' ELSE 'Non Abonné' END |
+-------------+------------------+-----------+----------+------------+------------------------------------------------------------+
|           1 | abe@example.com  | Abe       | Aaronson | 1965-12-31 | Abonné                                                     |
|           2 | bill@example.com | Bill      | Bond     | 1925-05-01 | Non Abonné                                                 |
+-------------+------------------+-----------+----------+------------+------------------------------------------------------------+

所以你可能在某处出现语法错误(这似乎是PHP字符串的一部分,而不是发送到MySQL服务器的最终SQL)。

我还建议使用列别名。按索引填充列非常容易出错:

... CASE WHEN newsletter=1 THEN 'Abonné' ELSE 'Non Abonné' END AS status

答案 2 :(得分:0)

使用IF()函数,它是一个mysql三元组。您可以使用AS对结果进行别名。