MYSQL查询条件语句

时间:2012-07-19 16:19:53

标签: mysql conditional-statements

我的查询有问题: 我有一张表,其中列出了客户下的订单

orders: customer_id, payment_method ...some other field

如果客户至少使用特定付款方式付款,我需要提取customer_id和'YES'

我试过这样的事情:

SELECT DISTINCT o.customer_id, 
CASE WHEN o.payment_method = 10 THEN 'YES' ELSE 'NO' END AS credit_card
FROM orders AS o
WHERE o.year = 2012
ORDER BY o.customer_id

但是如果客户使用不同的付款方式付款,则显示两条记录,一条带有“是”,一条带有“否”......可能只获得一个值?

2 个答案:

答案 0 :(得分:2)

SELECT   o.customer_id, 
         IF(MAX(IF(o.payment_method=10, 1, 0)) = 1, 'YES', 'NO') credit_card
FROM     orders o
WHERE    o.year = 2012
GROUP BY o.customer_id

答案 1 :(得分:0)

您可以使用group by进行自联接,并在连接表中测试NULL(未经测试):

SELECT customer_id, IF(p.customer_id IS NULL, 'NO', 'YES')
FROM orders o
LEFT OUTER JOIN orders p ON o.customer_id = p.customer_id AND p.payment_method = 10
    AND p.year = 2012
WHERE o.year = 2012
GROUP BY o.customer_id
ORDER BY o.customer_id

不确定问题是否需要p.year = 2012条件。