在子查询外部与列联接

时间:2019-10-10 08:29:22

标签: mysql

SELECT t1.name as r_name, t1.values as r_values
FROM table as t1
JOIN (
    SELECT SUM(amount) as amount
    FROM database2.table
    WHERE ids IN (t1.values)
) as t2
WHERE t1.id = 20;

我得到一个错误,即子查询中的t1.values是未知列。

2 个答案:

答案 0 :(得分:0)

您需要重写查询,并使zone_list = Zone.objects.filter( location_point__distance_lte=( shop.location_point, D(m=Cast('radius', output_field=models.FloatField())) ) ) 进入where条件:

join

此外,您不使用SELECT t1.name as r_name, t1.values as r_values FROM table as t1 JOIN ( SELECT SUM(amount) as amount FROM database2.table ) as t2 ON t2.ids = t1.values WHERE t1.id = 20; 列,那么amount的意义是什么?

另一个问题,您没有定义任何join条件。

我认为您首先需要阅读有关SQL中的join的知识:)

答案 1 :(得分:0)

似乎您正在尝试根据database2.table列表将t1加入您的t1.values。 由于您使用了汇总功能,因此我在t2中添加了ID分组。然后,不确定您的sum(amount)

的目的是什么
SELECT t1.name as r_name, t1.values as r_values
FROM table as t1
JOIN (
    SELECT SUM(amount) as amount, ids
    FROM database2.table
    GROUP BY ids
) as t2 on t2.ids IN (t1.values)
WHERE t1.id = 20;