以下SQL语句设置用户变量@id,然后我在尾随子查询中使用它。我的问题是@id变量只被设置为结果集中的第一个items.id - 而不是“每行” - 因此子查询的结果对于主选择中的每一行都是相同的。有谁知道是否有办法重置每行的@id变量?
select
items.id
,items.title
,@id := items.id
,(
select
group_concat(x.y)
from
(
select
group_concat(ledger.stockcode) as y
from
ledger
where
@id = ledger.itemid
group by
ledger.stockcode
having
sum(ledger.stockqty) > 0
) as x
) as extras
from
items
where
items.id = 196
答案 0 :(得分:0)
尝试此查询
select
a.id
,a.title
,b.y as extras
from
items a
inner join
(select
group_concat(ledger.stockcode) as y
from
ledger
where
ledger.itemid = 196
group by
ledger.stockcode
having
sum(ledger.stockqty) > 0) b
on
a.id = 196 AND a.id = b.itemid