这是我的工作查询:
SELECT
public."T1"."Id" AS "StuffId",
public."T1"."Name" AS "StuffName",
public."T3"."Id" AS "ThingId",
public."T3"."Name" AS "ThingName",
public."T4"."Id" AS "AnyId",
public."T4"."Name" AS "AnyName"
FROM public."T1"
INNER JOIN public."T2"
ON public."T1"."Id" = public."T2"."StuffId"
INNER JOIN public."T3"
ON public."T2"."Id" = public."T2"."ThingId"
INNER JOIN public."T4"
ON public."T4"."Id" = public."T2"."AnyId"
我想以一种更具可读性的方式使用别名来编写它,但是对于别名,它永远不会被确认。
我很了解Postgresql,但是我对SQL Server,My SQL和Oracle有很好的了解。
这就是我想要的:
SELECT
Stuff.Id AS "StuffId",
Stuff.Name AS "StuffName",
Thing.Id AS "ThingId",
Thing.Name AS "ThingName",
Any.Id AS "AnyId",
Any.Name AS "AnyName"
FROM public."T1" AS Stuff
INNER JOIN public."T2" AS Link
ON Stuff.Id = Link.StuffId
INNER JOIN public."T3" AS Thing
ON Thing.Id = Link.ThingId
INNER JOIN public."T4" AS Any
ON Any.Id = Link.AnyId
在第一个查询中应该有什么类似的内容?
答案 0 :(得分:1)
您要做的第一件事是摆脱标识符周围所有这些嘈杂的引号。在标准SQL中,标识符被视为不区分大小写(默认为大写),因此这3个(未加引号的)限定符在语法上是等效的:
... as FOO
... as foo
... as FoO
当确实需要混合大小写或标识符与保留关键字冲突时,可以使用带引号的标识符。
用例中的问题是,您不能从查询中删除引号,因为您的表最初是使用(带引号的)camelCase标识符创建的,例如:
CREATE TABLE T1 (
"Id" INT,
"Name" VARCHAR(100)
);
您需要RENAME
these columns到没有引号的内容:
ALTER TABLE T1 RENAME "Id" TO id;
ALTER TABLE T1 RENAME "Name" TO name;
要替换camelCase表示法中的大小写中断,我建议使用下划线字符:
ALTER TABLE T2 RENAME "StuffId" TO stuff_id;
所有表列均正确重命名后,即可运行以下查询:
SELECT
Stuff.Id AS Stuff_Id,
Stuff.Name AS Stuff_Name,
Thing.Id AS Thing_Id,
Thing.Name AS Thing_Name,
Any.Id AS Any_Id,
Any.Name AS Any_Name
FROM
T1 AS Stuff
INNER JOIN T2 AS Link ON Stuff.Id = Link.Stuff_Id
INNER JOIN T3 AS Thing ON Thing.Id = Link.Thing_Id
INNER JOIN T4 AS Any ON Any.Id = Link.Any_Id
答案 1 :(得分:0)
单词public
是SHEMA的名字。如果这是默认的数据库模式,那么您可能会在查询中错过它。像这样T1.Id
这样写就可以了。
如果此模式不是默认模式,那么您可以为某些数据库用户更改它,并与他Change default schema for user一起使用