gpt4 book ai didi

sql - JOIN语法中的MySQL相关子查询

转载 作者:IT老高 更新时间:2023-10-28 23:54:31 26 4
gpt4 key购买 nike

我想通过指定 innertable.id = outertable.id 为内部查询提供 WHERE 条件。但是,MySQL (5.0.45) 报告“'where 子句'中的未知列'outertable.id'”。这种查询可以吗?

内部查询使用 GROUP BY 将行转为列。这可以完全在外部查询中执行,但由于额外的连接可能会产生额外的开销。

或者,我可以在内部查询中省略 WHERE 条件,而是指定 ON outertable.id = innerquery.id,但它会获取整个内部查询行集以再次加入外部查询,这是低效的。

实际的 SQL 如下所示:

select t.ticketid, u.userid, t.fullname, u.loginapi_userid, t.email, tp.subject, tp.contents, a.PhoneNumber, a.Location, a.Extension, a.BusinessUnit, a.Department
from swtickets t
inner join swticketposts tp on t.ticketid = tp.ticketid
inner join swusers u on t.userid = u.userid
left join
(
select
cfv.typeid,
min(case cfv.customfieldid when 1 then cfv.fieldvalue end) as 'PhoneNumber',
min(case cfv.customfieldid when 3 then cfv.fieldvalue end) as 'Location',
min(case cfv.customfieldid when 5 then cfv.fieldvalue end) as 'Extension',
min(case cfv.customfieldid when 8 then cfv.fieldvalue end) as 'BusinessUnit',
min(case cfv.customfieldid when 9 then cfv.fieldvalue end) as 'Department'
from swcustomfieldvalues cfv
where cfv.typeid = t.ticketid
group by cfv.typeid
) as a on 1 = 1
where t.ticketid = 2458;

最佳答案

您的问题的答案是否定的,无法像您那样引用相关名称。派生表由内部查询在外部查询开始评估联接之前生成。因此,ttpu 等相关名称不可用于内部查询。

为了解决这个问题,我建议在内部查询中使用相同的常量整数值,然后在外部查询中使用真实条件而不是 1=1 连接派生表。

SELECT t.ticketid, u.userid, t.fullname, u.loginapi_userid, t.email,
tp.subject, tp.contents, a.PhoneNumber, a.Location, a.Extension,
a.BusinessUnit, a.Department
FROM swtickets t
INNER JOIN swticketposts tp ON (t.ticketid = tp.ticketid)
INNER JOIN swusers u ON (t.userid = u.userid)
LEFT OUTER JOIN (
SELECT cfv.typeid,
MIN(CASE cfv.customfieldid WHEN 1 THEN cfv.fieldvalue END) AS 'PhoneNumber',
MIN(CASE cfv.customfieldid WHEN 3 THEN cfv.fieldvalue END) AS 'Location',
MIN(CASE cfv.customfieldid WHEN 5 THEN cfv.fieldvalue END) AS 'Extension',
MIN(CASE cfv.customfieldid WHEN 8 THEN cfv.fieldvalue END) AS 'BusinessUnit',
MIN(CASE cfv.customfieldid WHEN 9 THEN cfv.fieldvalue END) AS 'Department'
FROM swcustomfieldvalues cfv
WHERE cfv.typeid = 2458
GROUP BY cfv.typeid
) AS a ON (a.typeid = t.ticketid)
WHERE t.ticketid = 2458;

关于sql - JOIN语法中的MySQL相关子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/530381/

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