如何在子查询

时间:2015-11-26 16:44:33

标签: mysql

我试图在子查询中使用名为children_ids的列的值:

SELECT hotels.id,
       hotels.hotel,
       hotels.country,
       hotels.corrected,
       hotels.children_type,
       hotels.children_ids as children_ids,
       (SELECT SUM(trx_input.count) FROM hotels LEFT JOIN trx_input ON hotels.trx_id = trx_input.id WHERE hotels.id IN (children_ids)) as count_children,
       trx_input.count
FROM hotels
LEFT JOIN trx_input ON hotels.trx_id = trx_input.id
WHERE hotels.country = 'DE' AND children_type != 2
ORDER BY hotels.hotel
LIMIT 1000

count_children总是NULL。如果我用一些实际值替换children_ids,它可以工作:

SELECT hotels.id,
       hotels.hotel,
       hotels.country,
       hotels.corrected,
       hotels.children_type,
       hotels.children_ids as children_ids,
       (SELECT SUM(trx_input.count) FROM hotels LEFT JOIN trx_input ON hotels.trx_id = trx_input.id WHERE hotels.id IN (338666,338665,338456,338691)) as count_children,
       trx_input.count
FROM hotels
LEFT JOIN trx_input ON hotels.trx_id = trx_input.id
WHERE hotels.country = 'DE' AND children_type != 2
ORDER BY hotels.hotel
LIMIT 1000

有没有办法在子查询中使用外部列的值?

2 个答案:

答案 0 :(得分:1)

您可以使用find_in_set()

执行您想要的操作
   (SELECT SUM(i.count)
    FROM hotels h2 JOIN
         trx_input i
         ON h2.trx_id = i.id
    WHERE find_in_set(h2.id, h.children_ids) > 0
   ) as count_children,

但是,您应该修复数据结构以使用正确的联结表。在逗号分隔列中存储id列表不是存储数据的正确方法。

答案 1 :(得分:0)

您可以用In替换In(children_ids)(从酒店hotls1中​​选择children_ids,其中hotels.id = hotels1.I' d)