SELECT语句返回行,但具有相同WHERE的SELECT COUNT(*)不返回(AWS AuroraDB)

时间:2019-05-13 14:13:50

标签: sql aws-aurora

这是与用户和GpsPosition相关的数据库架构:

CREATE TABLE GpsPosition 
(
    altitudeInMeters SMALLINT NOT NULL,
    dateCreated      BIGINT NOT NULL,
    dateRegistered   BIGINT NOT NULL,
    deviceId         BINARY(16) NOT NULL,
    emergencyId      BINARY(16) NULL,
    gpsFix           SMALLINT NOT NULL,
    heading          SMALLINT NOT NULL,
    horizontalUncertaintyInMeters SMALLINT NOT NULL,
    id               BINARY(16) NOT NULL,
    latestForDevice  BOOLEAN NOT NULL,
    latestForUser    BOOLEAN NOT NULL,
    latitude         DOUBLE PRECISION NOT NULL,
    longitude        DOUBLE PRECISION NOT NULL,
    numSatellites    SMALLINT NOT NULL,
    speedInKmph      SMALLINT NOT NULL,
    stale            BOOLEAN NOT NULL,
    userId           BINARY(16) NULL,
    verticalUncertaintyInMeters SMALLINT NOT NULL,

    PRIMARY KEY (id)
);

ALTER TABLE GpsPosition 
    ADD CONSTRAINT GpsPosition_deviceId_fkey 
        FOREIGN KEY (deviceId) REFERENCES Device(id) 
            ON UPDATE CASCADE ON DELETE CASCADE;

ALTER TABLE GpsPosition 
    ADD CONSTRAINT GpsPosition_emergencyId_fkey 
        FOREIGN KEY (emergencyId) REFERENCES Emergency(id) 
            ON UPDATE CASCADE ON DELETE SET NULL;

ALTER TABLE GpsPosition 
    ADD CONSTRAINT GpsPosition_userId_fkey 
        FOREIGN KEY (userId) REFERENCES User(id) 
            ON UPDATE CASCADE ON DELETE SET NULL;

ALTER TABLE GpsPosition 
    ADD CONSTRAINT deviceId_dateCreated_must_be_unique 
        UNIQUE (deviceId, dateCreated);

CREATE INDEX i2915035553 ON GpsPosition (deviceId);
CREATE INDEX deviceId_latestForDevice_is_non_unique ON GpsPosition (deviceId, latestForDevice);
CREATE INDEX i3210815937 ON GpsPosition (emergencyId);
CREATE INDEX i1689669068 ON GpsPosition (userId);
CREATE INDEX userId_latestForUser_is_non_unique ON GpsPosition (userId, latestForUser);

此语句返回很多行:

select *
from GpsPosition
where exists (select *
              from User
              where User.id = GpsPosition.userId and
                    User.id = UNHEX( '3f4163aab2ac46d6ad15164222aca89e' )
             );

此语句返回单行(结果),其值为0:

select count(*)
from GpsPosition
where exists (select *
              from User
              where User.id = GpsPosition.userId and
                    User.id = UNHEX( '3f4163aab2ac46d6ad15164222aca89e' )
             );

我不明白SELECT *语句如何返回许多结果,而SELECT COUNT(*)语句返回0。它们都具有相同的WHERE语句。

1 个答案:

答案 0 :(得分:0)

相关的子查询用于逐行处理。每个子查询对外部查询的每一行执行一次。此图对enter image description here有很大帮助 因为外部查询结果只包含GpsPosition中的一行数,所以结果为0。

我认为这应该可行:

select count(*) from (
    select *
    from GpsPosition
    where exists (select *
                  from User
                  where User.id = GpsPosition.userId and
                        User.id = UNHEX( '3f4163aab2ac46d6ad15164222aca89e' )
                 )
) view1