将数据从父级传递到子查询

时间:2017-10-26 21:54:15

标签: mysql sql

我正在尝试创建一个连接主查询的每一行的某些数据的查询,但我不知道如何解决'where子句'中的“未知列'cm.index'”。如何将父查询行的列值传递给子查询?

父查询中的每一行都有一个索引整数。我想计算消费指数大于每条消息索引的channel_members的数量。

Here是一个示例db

SELECT read_count.*, cm.*
FROM   chat_messages as cm
JOIN (SELECT b.chat_channel_id, Count(b.chat_channel_id) AS members_read 
    FROM   channel_members b
    WHERE  b.consumption_index >= cm.index 
    GROUP  BY b.chat_channel_id) read_count 
ON cm.channel_id = read_count.chat_channel_id
WHERE cm.channel_id=5;

1 个答案:

答案 0 :(得分:0)

您加入的子查询不是相关子查询,因此您无法将主查询中的列传递到其中,它们必须在ON条件下相关。 / p>

您应该更改子查询以在分组中包含cm.index。然后你可以加入。

SELECT cm.*, SUM(rc.members_read) AS members_read
FROM chat_messages AS cm
JOIN (SELECT chat_channel_id, consumption_index, COUNT(*) AS members_read
      FROM channel_members
      GROUP BY chat_channel_id, consumption_index) AS rc
ON cm.channel_id = rc.chat_channel_id AND rc.consumption_index >= cm.index
WHERE cm.channel_id = 5

或者你可以将它作为一个真实的相关子查询来实现,它位于SELECT列表中。

SELECT cm.*, 
    (SELECT COUNT(*)
    FROM channel_members AS b
    WHERE b.chat_channel_id = cm.channel_id AND b.consumption_index = cm.index) AS members_read
FROM chat_messages AS cm
WHERE cm.channel_id = 5