仅在主条目通过认证的情况下选择

时间:2018-10-29 08:30:08

标签: mysql

请考虑以下架构:

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

如果主条目未经认证,则不应显示子条目,您怎么知道它们是子条目?您会在子条目的主线程列中看到该条目,并为其分配了ID。

当前,即使我只选择了ID与子条目mainthread相同的主条目,它也会选择任何主条目

您可以看到主条目1未通过认证,但主条目4(没有子条目)为,并且仍显示主条目1的子条目。我在做什么错了?

2 个答案:

答案 0 :(得分:0)

如果您想获得std::map认证的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

答案 1 :(得分:0)

我找到了,我必须使用左联接,所以这是解决方案

    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