列在包含多个SELECT的SQL语句中返回空值

时间:2019-03-20 15:12:23

标签: mysql sql

我从以前的开发人员那里继承了特定的代码。我打算重新构建该应用程序,但是在继续之前,我必须添加一些功能。

首先,这是一个与会计有关的62列表,我还必须通过一次调用从不同的表中获取值,以获取插入前所需的值。

让我们说我需要在表dailysales中进行插入,并且我需要同时从表a,b,cd中获取值。 我已经有一条用于获取此值的sql语句,它工作正常,但特定列始终返回为NULL。 这是我的代码:

SELECT `gds_pnr_ref`, `transaction_date`,
       (SELECT `lastname` FROM `a` WHERE `id` = `staff` LIMIT 1) as `lastname`,
       (SELECT `firstname` FROM `a` WHERE `id` = `staff` LIMIT 1) as `firstname`,
       (SELECT `department_name` FROM `b` WHERE `id` = `staff_department` LIMIT 1) as `department`,
       (SELECT `name` FROM `b` WHERE `memo_serial` = '$some_value' LIMIT 1) as `pax_name`,
       (SELECT `customer_name` FROM `c` WHERE `id` = `customer_name` LIMIT 1) as `customer`,
       travel_product,
       (SELECT `vendor_name` FROM `c` WHERE `id` = `vendor` LIMIT 1) as `vendor` 
FROM `d` WHERE `id` = '$some_value' LIMIT 1

(SELECT customer_name FROM c WHERE id = customer_name LIMIT 1) as customer总是返回NULL,但是当我独立运行它时,它会给我适当的值。

我非常乐意寻求更好的解决方案。

2 个答案:

答案 0 :(得分:3)

您应始终限定查询中的列名。大概您打算这样:

SELECT d.`gds_pnr_ref`, d.`transaction_date`,
       (SELECT a.`lastname` FROM `a` WHERE a.`id` = d.`staff` LIMIT 1) as `lastname`,
       (SELECT a.`firstname` FROM `a` WHERE a.`id` = d.`staff` LIMIT 1) as `firstname`,
       (SELECT b.`department_name` FROM `b` WHERE b.`id` = d.`staff_department` LIMIT 1) as `department`,
       (SELECT b.`name` FROM `b` WHERE b.`memo_serial` = ? LIMIT 1) as `pax_name`,
       (SELECT c.`customer_name` FROM `c` WHERE c.`id` = d.`customer_name` LIMIT 1) as `customer`,
       d.travel_product,
       (SELECT c.`vendor_name` FROM `c` WHERE c.`id` = d.`vendor` LIMIT 1) as `vendor` 
FROM `d`
WHERE d.`id` = ?
LIMIT 1;

我必须猜测列的来源-因此可能不是100%正确。

请注意,我还用?占位符替换了字符串变量。提醒您应该为此类值使用参数。

答案 1 :(得分:1)

谢谢大家,但这是我最终进行的查询,它返回所有我需要的值,且non为null。

SELECT  `a`.`currency`, 
        `a`.`vendor_name`,
        CONCAT(`c`.`lastname`, ' ', `c`.`firstname`) AS `actioned_by`,
        `e`.`department_name` AS `department`,
        `f`.`customer_name` AS `customer`,
        `g`.`currency_name` AS `fl_currency`,
        `b`.`name`,
        `b`.`nuc`,
        `b`.`tax`,
        `b`.`comm` AS `comm_percen`,
        `b`.`comm_tax` AS `comm_tax_value`,
        `b`.`actual_comm`,
        `b`.`service_charge`,
        `b`.`dip`,
        SUM(`b`.`vendor`) AS payable,
        `b`.`charge` AS receivable
FROM ((((((`d`
INNER JOIN `b` ON `d`.`id` = `b`.`memo_serial`)
INNER JOIN `a` ON `d`.`vendor` = `a`.`id`)
INNER JOIN `c` ON `d`.`staff` = `c`.`id`) 
INNER JOIN `e` ON `d`.`staff_department` = `e`.`id`) 
INNER JOIN `f` ON `d`.`customer_name` = `f`.`id`) 
INNER JOIN `g` ON `a`.`currency` = `g`.`id`)  WHERE `d`.`id` = '$some_value'

使用子查询有一些限制,例如当我需要在特定表中提取特定外键的多个条目时。它一直只返回第一行值。所以我最终使用INNER JOIN从6个不同的表中提取结果,结果更加整洁