SELECT无法在UPDATE(Oracle)中工作

时间:2017-05-10 13:21:45

标签: sql oracle select

我想在Oracle SQL Developer中进行更新,并遵循以下代码:

std::map<int, int> map{ {4,3},{5,2},{7,2} };
std::list<std::pair<int, int>> list;
const int threshold = 6, window = 4;
for (auto it = map.begin(); it != map.end(); ++it)
{
    while (list.size() > 0 && it->first - list.front().first >= window)
        list.pop_front();
    list.push_back(*it);

    int count = 0;
    for (auto e : list)
        count += e.second;
    if (count > threshold)
        std::cout << "over threshold" << std::endl;
}
std::cout << "end" << std::endl;

当我运行SELECT

UPDATE DATABASE_1 
   SET  COLOR =        CASE WHEN COLOR IS NULL THEN '100'
                            WHEN COLOR = '100' THEN '100' ELSE COLOR      END,
        COLOR_UNIT  =  CASE WHEN COLOR_UNIT IS NULL THEN '%'
                            WHEN COLOR_UNIT = '' THEN '%' 
                            WHEN COLOR_UNIT = ' ' THEN '%' ELSE COLOR_UNIT END
WHERE ID IN    (SELECT t.ID
                FROM DATABASE_1 t
                JOIN DATABASE_2 s ON t.ID = s.ID AND t.SEQUENCE = s.SEQUENCE
                WHERE s.CRITERIA = 'HIGH' AND t.SEQUENCE = (SELECT MAX (te.SEQUENCE) FROM DATABASE_1 te WHERE te.ID = s.ID));

本身,它给了我正确的结果(如预期的那样)。

事情是,一旦我运行整个UPDATE语句,SELECT t.ID FROM DATABASE_1 t JOIN DATABASE_2 s ON t.ID = s.ID AND t.SEQUENCE = s.SEQUENCE WHERE s.CRITERIA = 'HIGH' AND t.SEQUENCE = (SELECT MAX (te.SEQUENCE) FROM DATABASE_1 te WHERE te.ID = s.ID) 部分就会被忽略,然后它会更新更多行(每个条目与给定的ID匹配,并且AND t.SEQUENCE = (SELECT MAX (te.SEQUENCE) FROM DATABASE_1 te WHERE te.ID = s.ID)为真)。

1 个答案:

答案 0 :(得分:1)

我对您的查询与您预期的更多行匹配并不感到惊讶 - 假设您只想更新每个ID最新序列的行。

您的子查询实际上是在检查每个id,其中一行的序列与最大序列值匹配。只要表格中的每个id至少有一行,这一直都是真的!

相反,我认为你追求的是:

UPDATE DATABASE_1 
   SET  COLOR =        CASE WHEN COLOR IS NULL THEN '100'
                            WHEN COLOR = '100' THEN '100' ELSE COLOR      END,
        COLOR_UNIT  =  CASE WHEN COLOR_UNIT IS NULL THEN '%'
                            --WHEN COLOR_UNIT = '' THEN '%'  -- totally irrelevant; there is no such thing as an empty string in Oracle (it is treated as NULL). Remove this.
                            WHEN COLOR_UNIT = ' ' THEN '%' ELSE COLOR_UNIT END
WHERE (ID, SEQUENCE) IN (SELECT t.ID, t.sequence
                         FROM DATABASE_1 t
                         JOIN DATABASE_2 s ON t.ID = s.ID AND t.SEQUENCE = s.SEQUENCE
                         WHERE s.CRITERIA = 'HIGH' AND t.SEQUENCE = (SELECT MAX (te.SEQUENCE) FROM DATABASE_1 te WHERE te.ID = s.ID));