如何将这些查询与另一个父表中的where子句组合成一个查询



如何将这些查询与另一个父表中的where子句组合成一个查询?请考虑我的SQL代码,并建议一种更好的方法来使用

//look my code
CREATE TABLE IF NOT EXISTS first (
fid int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
p_name varchar(60) NOT NULL
);
CREATE TABLE IF NOT EXISTS second (
sed int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
firstname varchar(20) NOT NULL,
fid int(11) NOT NULL,
FOREIGN KEY (fid) REFERENCES first(fid)
);
CREATE TABLE IF NOT EXISTS third (
thid int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
start_date date NOT NULL,
end_date date NOT NULL,
sed int(11) NOT NULL,
FOREIGN KEY (sed) REFERENCES second(sed),
fid int(11) NOT NULL,
FOREIGN KEY (fid) REFERENCES first(fid)
);
CREATE TABLE IF NOT EXISTS fourth (
fid int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
start_date date NOT NULL,
end_date date NOT NULL,
sed int(11) NOT NULL,
FOREIGN KEY (sed) REFERENCES second(sed),
fid int(11) NOT NULL,
FOREIGN KEY (fid) REFERENCES first(fid)
);
CREATE TABLE IF NOT EXISTS fifth (
fiid int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
start_date date NOT NULL,
end_date date NOT NULL,
sed int(11) NOT NULL,
FOREIGN KEY (sed) REFERENCES second(sed),
fid int(11) NOT NULL,
FOREIGN KEY (fid) REFERENCES first(fid)
);
CREATE TABLE IF NOT EXISTS sixth (
sid int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
start_date date NOT NULL,
end_date date NOT NULL,
sed int(11) NOT NULL,
FOREIGN KEY (sed) REFERENCES second(sed),
fid int(11) NOT NULL,
FOREIGN KEY (fid) REFERENCES first(fid)
);


//As you can see above, I want to create a single query to query all data at the samee time i.e
//All table from third table depend on first and second table, but the second table have column firstname and the first table has the p_name column

//I want 
SELECT second.*, third.* FROM second INNER JOIN third ON third.sed = second.sed
SELECT second.*, fourth.* FROM second INNER JOIN fourth ON fourth.sed = second.sed
SELECT second.*, fifth.* FROM second INNER JOIN fifth ON fifth.sed = second.sed
SELECT second.*, sixth.* FROM second INNER JOIN sixth ON sixth.sed = second.sed

....WHERE fid = 1;

我想将这些查询组合成一个单独的查询,即$newquerys='..';

概念

第二张表用来记录所有细节,即学生的详细信息,但第三到第六张表几乎没有不同的细节,但它们从第二张表格中提取了所有其他细节,即一名学生可以担任主席、秘书和副秘书,但不是所有学生,所以我把他们分在第三到六张表中。第一张表过去只保存一些关于班级的信息,所以我想根据班级表来区分主席等,但他们都是学生

简而言之,

主席、秘书和副秘书都是学生,但并不是所有学生都在一个班级中扮演这些角色,但我们有不止一个班级,如何根据班级区分这些领导者在单个查询中

您可以使用左联接

SELECT second.*, third.*,fourth.*,fifth.*,sixth.* FROM second 
LEFT JOIN third ON third.sed = second.sed
LEFT JOIN fourth ON fourth.sed = second.sed
LEFT JOIN fifth ON fifth.sed = second.sed
LEFT JOIN sixth ON sixth.sed = second.sed

WHERE second.fid = 1;

我假设,若学生是主席,那个么第三张表中会有该学生的条目。如果学生是普通学生,则上述查询将返回null。如果您也想要角色,您可以使用CASE语句。例如,

CASE WHEN third.startdate IS NULL THEN '' ELSE 'Chairman' END

最新更新