开发者

control flow with IF in mysql request

I would like to return a value based on the contents of a column in a mysql table.

example: if 'newsletter' = 1 return "Subscriber" else "not subscribed"

I tried with this syntax :

SELECT `id_customer`, `email`, `firstname`, `lastname`, `birthday`,
                    CASE WHEN `newsletter`=1 THEN "Abonné" ELSE "Non Abonné" END
                    FROM `"._DB_PREFIX_."customer`
                    ORDER BY `last开发者_如何学Goname` ASC

And it does absolutely not work.

A little help please?


Try to use

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


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

Your original query (I just got rid of backticks and replaced ANSI quotes with standard quotes and not because they are wrong):

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

... prints:

+-------------+------------------+-----------+----------+------------+------------------------------------------------------------+
| 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é                                                 |
+-------------+------------------+-----------+----------+------------+------------------------------------------------------------+

So you probably have a syntax error somewhere (this appears to be part of a PHP string rather than the final SQL sent to the MySQL server).

I'd also advise to use a column alias. Fechting columns by index is pretty error-prone:

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


Use the IF() function, which is a mysql ternary. You can alias the result using AS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜