仅当主条目经过认证时才选择

oug3syen  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(383)

请考虑以下模式:

CREATE TABLE users 
(
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(30) NOT NULL
);

CREATE TABLE mashup_x 
(
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    date VARCHAR(255),
    warranty VARCHAR(30) NOT NULL,
    userid VARCHAR(30) NOT NULL,
    mainthread VARCHAR(50),
    certified VARCHAR(50)
);

INSERT INTO users VALUES (1, "John");
INSERT INTO users VALUES (2, "Adam");

INSERT INTO mashup_x
VALUES (1, 1540804136000, 1, 2, 1, 0); /*this is a main entry with sub entries below*/

INSERT INTO mashup_x
VALUES (2, 1540804256000, 1, 1, 1, 1);

INSERT INTO mashup_x
VALUES (3, 1540804256000, 1, 1, 1, 1);

INSERT INTO mashup_x
VALUES (4, 1540804136000, 1, 2, 4, 1); /*this is a main entry with NO sub entry below*/

尝试的查询:

select 
    mashup_x.id as ok, users.name, mashup_x.certified, mashup_x.mainthread 
from 
    mashup_x, users 
where 
    users.id = mashup_x.userid 
    and certified = 1 
    and mashup_x.id != mainthread 
    and (select certified from mashup_x 
         where id = mainthread and id = mashup_x.id and certified = 1) = 1
order by 
    mashup_x.date desc

http://sqlfiddle.com/#!9/0f3537/1号楼
如果主条目未经认证,则不应显示子条目,您如何知道它们是子条目?您可以在子条目的mainthread列中看到,子条目被分配了maintry的id。
当前它选择任何主条目,即使我只选择了一个id与子条目主线程相同的条目
正如你所看到的,主条目1没有被认证,但是主条目4(没有子条目)被认证,它仍然显示主条目1的子条目。我做错什么了?

kse8i1jr

kse8i1jr1#

如果你想证明 subEntries 认证的 mainEntries 因此,您可以尝试以下代码:

select mashup_x.id as ok, users.name, mashup_x.certified, mashup_x.mainthread 
from mashup_x left join users on mashup_x.userid = users.id
where mashup_x.mainthread in (
    select mashup_x.id
    from mashup_x
    where mashup_x.certified = 1 and mashup_x.id = mainthread
)
and certified = "1" and mashup_x.id != mainthread
order by mashup_x.date desc

如您所见,我尝试通过中的子查询筛选主条目 Where 条款。另外,请考虑使用标准脚本 join .

deikduxw

deikduxw2#

我发现了它,我不得不使用左连接,所以这是解决方案

SELECT 
      * 
   FROM 
      mashup_x ta
         LEFT JOIN mashup_x Lta 
            ON ta.mainthread = Lta.id
         LEFT JOIN users xa 
            ON xa.id = ta.userid

   WHERE 
           ta.certified = 1 and ta.id != ta.mainthread AND Lta.id = Lta.mainthread
        AND Lta.certified = 1

相关问题