假设我有这四张桌子。
PEOPOLE
ID NAME SURNAME COMPANY UNIT GROUPS
--------------------------------------------
1 Michael Backer 1 1 1
2 Travis Morgan 2 2 2
3 George Marshall 3 3 3
COMPANY
ID NAME
------------
1 Coca Cola
2 Pepsi
3 Sprite
工作单元
ID NAME
-------------
1 Finances
2 Marketing
3 Sales
组(两个值都可以为空)
ID NAME FLOOR
-------------------------
1 Risks 5
2 NULL NULL
3 Secretariat NULL
预期结果
NAME SURNAME COMPANYNAME WORKUNIT GROUPS FLOOR
-----------------------------------------------
Michael Backer Coca Cola Finances Risks 5
Travis Morgan Pepsi Marketing NULL NULL
George Marshall Sprite Sales Secretariat NULL
到目前为止,我写这个查询没有成功:
SELECT
people.NAME, people.SURNAME, company.NAME,
workunit.NAME, groups.NAME, groups.FLOOR
FROM
company, workunit, groups, people
LEFT JOIN
groups on people.GROUP = GROUPS.id
WHERE
company.id = people.company AND
workunit.id = people.unit AND
groups.id = people.group AND
groups.floor = 'something from textbox';
我不熟悉在多个表中组合连接语句,所以请帮助我,因为我被卡住了。
答案 0 :(得分:1)
就这样写:
SELECT
people.NAME,
people.SURNAME,
company.NAME,
workunit.NAME,
groups.NAME,
groups.FLOOR
FROM
people
INNER JOIN GROUP
ON people.GROUP=GROUPS.id
INNER JOIN company
ON people.company=company.id
INNER JOIN UNIT
ON people.UNIT =UNIT.id
WHERE
GROUPS.floor='something from textbox';
答案 1 :(得分:0)
我在SQL Server中验证了您的查询。你需要稍微修改它,以便以这种方式看它的执行:
SELECT
people.NAME, people.SURNAME, company.NAME,
workunit.NAME, groups.NAME, groups.FLOOR
FROM
company, workunit, people
LEFT JOIN
groups on people.GROUP = GROUPS.id
WHERE
company.id = people.company AND
workunit.id = people.unit AND
groups.id = people.group AND
groups.floor = 'something from textbox';
无论如何,您的查询不起作用,因为即使您希望使用LEFT JOIN
描述的方式得到结果,您也要设置条件:
AND groups.floor = 'something from textbox';
通过这种方式,您将无法看到与GROUPS
表不匹配的记录,因为您明确表示您希望记录中列的值floor
必须等于'something from textbox'
。
如果您还想要不匹配,您可以将条件替换为:
OR groups.floor = 'something from textbox';
但是你会有一些重复,而group by
语句无论如何都不会起作用。
然后,你必须检查你是否真的想要那些预期的结果。
我不明白为什么你也想要非匹配,即使你正在寻找使用groups.floor = 'something from textbox'
的精确结果。如果你想在GUI中显示结果,我认为不匹配对用户来说是无用的信息。
答案 2 :(得分:-1)
SELECT people.NAME, people.SURNAME, company.NAME, workunit.NAME, groups.NAME, groups.FLOOR
FROM company, workunit, groups LEFT JOIN people on people.GROUP=GROUPS.id
WHERE
company.id=people.company AND
workunit.id=people.unit AND
groups.id=people.group AND
groups.floor='something from textbox';