在格式化和可读性方面,SQL似乎是最被忽视的语言......而且由于SQL语句可能非常详细和复杂,因此使用起来非常困难。但我发现当我尝试以尽可能最好的方式格式化我的SQL代码时,我有时候不确定如何去做。我知道Java,C#,Python等的标准......但是当涉及到SQL时,我没有看到太多指南或接受的做法。什么是格式化SQL的提示/规则,以便它清晰,清晰,合乎逻辑?你能给出示例代码来说明吗?您发现什么是格式化SQL的最标准,可接受的方式?
答案 0 :(得分:11)
您可以尝试查看Joe Celko的书SQL Programming Style。我敢肯定有很多人不同意他的风格,但这是一个好的开始。
我自己的一些“规则”
例如:
SELECT
column_1,
column_2,
CASE
WHEN column_5 = 'Blah' THEN 1
WHEN column_6 = 'Blah' THEN 2
ELSE 3
END AS column_alias
FROM
My_Table MT
INNER JOIN My_Other_Table MOT ON
MOT.column_1 = MT.column_1
WHERE
MT.column_2 = 'Some Value' AND
(
MT.column_3 = 'Some other value' OR
MT.column_4 = 'Some other value'
)
答案 1 :(得分:4)
答案 2 :(得分:2)
我通常遵循MSSQL Server的这种语法
SELECT statemenets
SELECT //optionally specify top or distinct
Field1,
Field2,
CASE WHEN (1 = 1) THEN
"1"
ELSE
"2"
END AS Field3,
...
FROM Table1 t1
INNER JOIN Table2 t2
ON t2.field1 = t1.field1 //I always reference the joined tables field name first
LEFT OUTER JOIN Table3 t3
ON (t3.field1 = t1.field1
AND t3.field2 = t2.field2) //I specify and with a new line and tabbed in
OR // I specify or(s) on thier own line this way you can distinguish from the two conditionals that need to be met
(t3.field1 = t2.field1
AND t3.field2 = t1.field2)
WHERE
(t1.Field1 = 'foo'
AND t1.field2 = 'bar')
OR
(t2.Field1 = 'foo'
AND t1.field2 = 'bar')
选择
中的派生表格Select
Field1,
Field2,
...
FROM (Select
Field1,
Field2,
Field3)
FROM Table1
WHERE
Field1 = '1') t1
更新语句
UPDATE Table1
SET
Field1 = 1,
Field2 = 2,
Field3 = 3
WHERE
(Field1 = 2
AND Field3 = 2)
OR
(Field3 = 1)
插入语句
INSERT INTO Table1
(Field1,
Field2,
Field3,
...)
VALUES
(1,
2,
3,
...)
如果声明
IF (some condition) BEGIN
END ELSE BEGIN
END
<强>程序强>
CREATE PROCEDURE Foo (
Bar INT,
Foo VARCHAR(20)
) AS
BEGIN
//Your Code Here
END
答案 3 :(得分:1)
我使用以下规则:
select height,width,age from person where width = 20
SELECT height, width, age FROM person WHERE (width = 20)
小写所有表名。永远不要在表名中使用camelcase(donkeyWrench)(如果你手工创建查询,你会在头脑中射击)。
始终在WHERE和HAVING子句中使用括号。在操作员之间使用空间。
... where width=20 and height>20
WHERE (width = 20) AND (height > 20)
示例:
/*Executed from xyz.php*/
SELECT
p.height, p.width, p.age,
pd.hastel, pd.hasmobile
FROM
person p
LEFT JOIN personaldata pd ON p.id_person = pd.id_person
LEFT JOIN relatives r ON pd.id_person = r.id_person
WHERE
( p.width = 20 ) AND
( (p.height > 20) AND (p.height < 15) ) AND
( pd.hastel)
ORDER BY
p.age, p.height