内部SELECT不能使用外部SELECT中的`u.id`

时间:2016-07-26 09:37:20

标签: mysql

我有以下MySQL查询:

SELECT
    COUNT(b.`id`) AS todayOverdue,
    DATE_FORMAT(t.`created_time`, "%Y%m%d") AS days
FROM
    `Bill` b
LEFT JOIN `Order` o ON b.`order_id` = o.`id`
LEFT JOIN `Trade` t ON o.`trade_id` = t.`id`
LEFT JOIN `User` u ON b.`user_id` = u.`id`
WHERE
b. `deadline` <= "' . $todayTime . '" 
AND b. `deadline` >= "' . $todayDate . '" 
AND b.`is_paid` = 0
AND (
    SELECT
        COUNT(b2.`id`)
    FROM
        `Bill` b2
    WHERE
        b2.`deadline` <= "' . $todayTime . '"
    AND b2.`user_id` = u.`id`
    AND b2.`is_paid` = 0
    OR (
        b2.`deadline` <= b2.`paid_time`
        AND b2.`is_paid` = 1
    )
) < 2
GROUP BY
    days

为什么内部SELECT不能使用外部SELECT中的u.id

1 个答案:

答案 0 :(得分:0)

内部选择完全独立于外部选择。 u表在外部选择中以内部选择未知的方式连接。

当你有

AND b2.`user_id` = u.`id` 

将你的哪一行与b2中的哪一行进行比较?服务器无法知道,因此您需要定义表u2并将其连接到内部选择中。