我有五个表,但两个是主表。 表itemy是可以在其中找到所有项目的表。桌子obchody_parovani,这是我们可以在其中找到与某些商店相关的商品的桌子。
表项
ID | nazev | cesta | druh | kvalita
1 | nazev | cesta | 1 | 1
2 | nazev | cesta | 3 | 2
3 | nazev | cesta | 1 | 1
4 | nazev | cesta | 5 | 3
表obchody_parovani
ID | obchod | item
1 | 1 | 2
2 | 3 | 3
3 | 1 | 1
我需要识别商品是否在商店中。如果是,那么我需要商店的ID,如果不是,则需要NULL。
我想要从obchody_parovani中获得结果的结果是ID 1
ID | nazev | cesta | druh_n | kvalita_n | obchod
1 | nazev | cesta | 1 | 1 | NULL
2 | nazev | cesta | 3 | 2 | 1
3 | nazev | cesta | 1 | 1 | NULL
4 | nazev | cesta | 5 | 3 | 1
nazev,cesta,druh_n,kvalita_n不重要,我需要列阻塞。如果表包含obchod = 1的行,则结果为1,否则为NULL
我当前的SQL是:
SELECT i.id, i.nazev, i.cesta, d.druh AS druh_n, k.nazev AS kvalita_n, par.obchod FROM itemy AS i LEFT JOIN itemy_druhy AS d ON d.id = i.druh LEFT JOIN itemy_kvalita AS k ON k.id = i.kvalita LEFT JOIN itemy_rozdeleni AS r ON r.id = i.rozdeleni LEFT JOIN obchody_parovani AS par ON par.item = i.id WHERE par.obchod = 1
答案 0 :(得分:0)
您可以尝试基于OUTER JOIN
表使用Itemy
。
模式(MySQL v5.7)
CREATE TABLE Itemy(
ID INT,
nazev VARCHAR(50),
cesta VARCHAR(50), druh INT, kvalita INT
);
INSERT INTO Itemy VALUES (1,'nazev','cesta',1,1);
INSERT INTO Itemy VALUES (2,'nazev','cesta',3,2);
INSERT INTO Itemy VALUES (3,'nazev','cesta',1,1);
INSERT INTO Itemy VALUES (4,'nazev','cesta',5,3);
CREATE TABLE obchody_parovani(
ID INT,
obchod INT,
item INT
);
INSERT INTO obchody_parovani VALUES (1, 1,2);
INSERT INTO obchody_parovani VALUES (2, 3,3);
INSERT INTO obchody_parovani VALUES (3, 1,1);
查询#1
SELECT i.*,op.obchod
FROM Itemy i
LEFT JOIN obchody_parovani op on i.druh = op.obchod
and i.kvalita = op.item
order by i.id;
| ID | nazev | cesta | druh | kvalita | obchod |
| --- | ----- | ----- | ---- | ------- | ------ |
| 1 | nazev | cesta | 1 | 1 | 1 |
| 2 | nazev | cesta | 3 | 2 | |
| 3 | nazev | cesta | 1 | 1 | 1 |
| 4 | nazev | cesta | 5 | 3 | |
从您尝试过的查询中,我认为您可以尝试将par.obchod = 1
的条件从on
移到where
子句,否则您将从inner join
进行obchody_parovani
< / p>
SELECT i.id, i.nazev, i.cesta, d.druh AS druh_n, k.nazev AS kvalita_n, par.obchod
FROM itemy AS i
LEFT JOIN itemy_druhy AS d ON d.id = i.druh
LEFT JOIN itemy_kvalita AS k ON k.id = i.kvalita
LEFT JOIN itemy_rozdeleni AS r ON r.id = i.rozdeleni
LEFT JOIN obchody_parovani AS par ON par.item = i.id and par.obchod = 1