簡體   English   中英

為什么我在子查詢和查詢中得到不同的結果?

[英]Why am I getting different results on a subquery and query?

我有下表' client_ticket_thread ':

create table client_ticket_thread
(
    id                bigint unsigned auto_increment
        primary key,
    client            bigint unsigned                       not null,
    category          varchar(255) collate utf8mb4_bin      not null,
    subject           varchar(512) collate utf8mb4_bin      not null,
    message_count     int unsigned default 0                not null,
    client_read       bit          default b'1'             not null,
    closed            bit          default b'0'             not null,
    time_created      int unsigned default unix_timestamp() not null,
    time_last_message int unsigned default 0                not null,
    time_closed       int unsigned default 0                not null,
    constraint client_ticket_thread_client_credential_id_fk
        foreign key (client) references client_credential (id)
);

此表中的條目之一如下:

7,1,General Inquiry,Thread X,1,true,false,1641790706,1641790707,0

我正在嘗試為特定目的編寫查詢,因此我需要來自其他表的外部數據,因此在子查詢中,我嘗試使用以下語句檢索closed的字段:

select (select ctt.closed from client_ticket_thread ctt where ctt.id=7 and ctt.client=1 limit 1) as thread_active;

但結果返回true

但是,以下語句按預期返回false

select closed as thread_active from client_ticket_thread where id=7 and client=1 limit 1;

當我嘗試檢索不同的字段時,例如subject ,我得到了正確的結果。 什么可能導致此錯誤?

注意:我正在使用 MariaDB 10.7.1

問題是您使用的是位字段。 由於這似乎是一個標志,我建議您將其更改為 boolean。 當使用 boolean 時,它在每種情況下都按預期返回 0/false。

這是一個dbfiddle.uk ,顯示了我的意思。

create table client_ticket_thread
(
    id                bigint unsigned auto_increment
        primary key,
    client            bigint unsigned                       not null,
    category          varchar(255) collate utf8mb4_bin      not null,
    subject           varchar(512) collate utf8mb4_bin      not null,
    message_count     int unsigned default 0                not null,
    client_read       bit          default b'1'             not null,
    closed            bit          default b'0'             not null,
    client_read_bool boolean default true not null,
    closed_bool boolean default false not null,
    time_created      int unsigned default unix_timestamp() not null,
    time_last_message int unsigned default 0                not null,
    time_closed       int unsigned default 0                not null
);

insert into client_ticket_thread
values
(7,1,'General Inquiry','Thread X',1,1,0,true,false,1641790706,1641790707,0)

select (
select closed_bool
from client_ticket_thread ctt 
where ctt.id=7 
and ctt.client=1 
) as thread_active;

我發現位字段實際上從子查詢返回了 48 的值,我想在你的情況下它被轉換為“真”,而沒有子查詢則為 0。 我不知道為什么它會返回 48。

在這里通讀了 bit 數據類型的文檔。

位以二進制形式返回,因此要顯示它們,要么加 0,要么使用 function(例如 HEX、OCT 或 BIN)來轉換它們。

因此,您可以首先使用 boolean,也可以使用SELECT (SELECT closed+0 FROM...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM