Tay*_*ing 18 mysql sql join subquery entity-attribute-value
我想通过指定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;
Run Code Online (Sandbox Code Playgroud)
Bil*_*win 30
您的问题的答案是否定的,不可能像您一样引用相关名称.在外部查询开始评估联接之前,派生表由内部查询生成.所以内部查询的相关名称如t,tp和u,不可用.
为了解决这个问题,我建议在内部查询中使用相同的常量整数值,然后使用实际条件而不是在外部查询中连接派生表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;
Run Code Online (Sandbox Code Playgroud)