gpt4 book ai didi

mysql - 包含多个 SELECT 的 SQL 语句中的一列返回空值

转载 作者:行者123 更新时间:2023-11-29 04:32:45 25 4
gpt4 key购买 nike

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

首先,这是一个与会计有关的 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 但是当我独立运行它时,它会给我适当的值。

我非常愿意接受更好的解决方案来解决这个问题。

最佳答案

您应该始终限定查询中的列名。据推测,您打算这样:

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% 正确。

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

关于mysql - 包含多个 SELECT 的 SQL 语句中的一列返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55264167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com