我正在尝试编写一个子查询以包含更大的查询,我正在编写的子查询需要从主列获取a.workorder_id
这个有用(注意x.workorder_id ='805')
SELECT a.* ,
( SELECT SUM( maxes ) qty
FROM (
SELECT MAX( qty ) maxes
FROM `rework_line` x
WHERE x.workorder_id = '805'
GROUP BY x.size
) as tba
) tmpsum
FROM rework_line a
WHERE a.workorder_id = '805'
GROUP BY a.workorder_id
然而,当我更改x.workorder_id = a.workorder_id时,它不再起作用并告诉我
#1054 - 'where子句'中的未知列'a.workorder_id'
SELECT a.* ,
( SELECT SUM( maxes )
qty FROM (
SELECT MAX( qty ) maxes
FROM `mtborah_rework_line` x
WHERE x.workorder_id = a.workorder_id
GROUP BY x.size
) as tba
) tmpsum
FROM mtborah_rework_line a
WHERE a.workorder_id = '805'
GROUP BY a.workorder_id
我确信这很简单,我忘记了,但是在我所有的googing中我都找不到怎么做,我也试着在freenode的mysql房间里询问,而他们所说的只是将它重写为加入,这是不可能的,因为我有它的查询如果我重新加入这个表它将通过我的计数和总和
答案 0 :(得分:3)
也许我错过了一些东西,但为什么不用连接中的子查询而不是相关的子查询来重写它:
SELECT a.*, qty
FROM mtborah_rework_line a
LEFT JOIN
(
SELECT SUM(maxes) qty, workorder_id
FROM
(
SELECT MAX( qty ) maxes, x.workorder_id
FROM `mtborah_rework_line` x
GROUP BY x.size, x.workorder_id
) m
GROUP BY workorder_id
) q
on a.workorder_id = q.workorder_id
WHERE a.workorder_id = '805';
甚至这样:
SELECT a.*, SUM(maxes) qty
FROM mtborah_rework_line a
LEFT JOIN
(
SELECT MAX(qty) maxes, x.workorder_id
FROM `mtborah_rework_line` x
GROUP BY x.size, x.workorder_id
) q
on a.workorder_id = q.workorder_id
WHERE a.workorder_id = '805'
GROUP BY a.workorder_id;