mysql - 连接在选择查询中不起作用

标签 mysql concatenation

我们正在从数据库中获取订购产品的列表,包括与订单表的连接。

我们希望根据传递的产品 ID 列出所有订单,以及每个订单中订购的产品数量。我们还想显示下订单的客户名称。因此,根据我们的知识,我们创建了一个查询来获取项目:

SELECT 
  `main_table`.*, 
  `order`.*, 
  SUM(main_table.qty_ordered - main_table.qty_canceled) AS `custom_qty`, 
  SUM(main_table.row_total) AS `custom_row_total`, 
  SUM(main_table.tax_amount) AS `tax_amount`, 
  SUM(main_table.hidden_tax_amount) AS `hidden_tax_amount`, 
  SUM(main_table.discount_amount) AS `discount_amount`, 
  CONCAT(order.customer_firstname, ' ' ,order.customer_middlename, ' ', order.customer_lastname) AS full_name 
FROM `sales_flat_order_item` AS `main_table` 
INNER JOIN `sales_flat_order` AS `order` ON main_table.order_id=order.entity_id 
WHERE (((((main_table.product_id = '902') OR (main_table.product_id = '903') OR (main_table.product_id = '904'))))) AND (main_table.store_id = '1') AND (CONCAT(order.customer_firstname, order.customer_middlename, order.customer_lastname) like '%rag%') 
GROUP BY `main_table`.`sku`  

除了 concat() 之外,上述查询中使用的所有聚合函数都工作正常。每次我们都会得到 full_name 列的值为 NULL,即使我们已经命名了相应的连接列。

请任何人帮助我找出为什么这不起作用。我们在上面的查询中做错了什么吗?

提前致谢。

最佳答案

由于 CONCAT() 如果任何参数为 NULL 则返回 NULL 我猜这三个参数之一可能是 NULL

尝试使用 CONCAT_WS() 函数(因为无论如何都使用分隔符)来跳过空值。

CONCAT_WS(' ', order.customer_firstname, order.customer_middlename, order.customer_lastname) AS full_name

参见the documentation了解更多信息。

附注:您可能想了解如何使用表别名来缩短查询文本并使其更具可读性。

关于mysql - 连接在选择查询中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28737150/

相关文章:

php - MySQL 表格式化

excel - 使用 CONCAT 执行部分搜索,不起作用

mysql - '+' 附近的 SQL 语法不正确

r - 遍历列表 R

MySQL 创建带有值的函数语句并返回数据类型decimal

php - 全局搜索字段搜索多列

MySQL 函数没有返回任何值

swift - 在 Swift 中连接字符串和整数

Java高效文件写入: String concatentation versus extra call to write()

Mysql查询查找特定列数据重复的行