Mysql简单查询问题

时间:2011-09-28 21:13:19

标签: mysql

我写了这个Mysql查询,但为customers_telephone表返回了很多空白字段 因为它从来都不是必需的领域。我想在我的网站上返回一些虚拟数据 如果字段为NULL,则查询(不将其插入数据库)。我知道MySQL 使用if子句但我认为它只用于创建数据库或......?

这是我的印章

SELECT orders.orders_id AS recipient_id, delivery_company, delivery_street_address, delivery_city, delivery_postcode, delivery_state, delivery_country, customers_telephone
FROM orders, orders_products
WHERE orders.orders_id = orders_products.orders_id
AND products_id = 416
ORDER BY `orders`.`orders_id` DESC

更新

我试过这样做,但它仍然无效,也许我在错误的地方做过?

SELECT orders.orders_id AS recipient_id, delivery_company, delivery_street_address, delivery_city,  delivery_postcode, delivery_state, delivery_country, IFNULL(customers_telephone, 'no number') AS customers_number
FROM orders, orders_products
WHERE orders.orders_id = orders_products.orders_id
AND products_id = 416
ORDER BY `orders`.`orders_id` DESC

返回

recipient_id    delivery_company    delivery_street_address     delivery_city       delivery_postcode   delivery_state  delivery_country    number
191743          This Chick Bakes    31-31 48th Ave #B           Long Island City    11101               NY              United States       917.848.6437
191724                              44 Miraflores Ave (studio)  San Rafael          94901               CA              United States    
191723                              397 South River Street      Wilkes-Barre        18702               PA              United States    

2 个答案:

答案 0 :(得分:3)

如果字段为NULL,请使用IFNULL函数提供值:

IFNULL(customers_telephone, 'dummydata') AS customers_telephone

IFNULL是一个非标准的MySQL扩展。标准方法是使用COALESCE函数来实现此目的。 MySQL也支持COALESCE,但它比IFNULL略慢,尽管这可能无关紧要。

答案 1 :(得分:1)

单程

SELECT COALESCE(customers_telephone, 'no number') FROM ...