714
edits
Tag: 2017 source edit |
|||
| Line 270: | Line 270: | ||
==SQL编码规则== | ==SQL编码规则== | ||
* | *别名/字段命名的使用 | ||
在进行 select 时,可以使用别名来简化查询的编写和阅读: | |||
<syntaxhighlight lang="sql"> | <syntaxhighlight lang="sql"> | ||
select chp1, chpxxx2 as chp2 from table2 as t1, table2 as t2 where t1.chpx = t2.chpy | select chp1, chpxxx2 as chp2 from table2 as t1, table2 as t2 where t1.chpx = t2.chpy | ||
</syntaxhighlight> | </syntaxhighlight> | ||
* | 但是,不应在 update 请求中使用别名,因为它们与 MySQL 3.1 不兼容。 | ||
*禁止使用 SELECT * !每个 SELECT 都必须指定要检索的字段的完整列表。这有助于避免混淆。最重要的是,这使代码的重新生成更加容易,并使变更对字段的影响分析成为可能。示例: | |||
<syntaxhighlight lang="sql"> | <syntaxhighlight lang="sql"> | ||
| Line 284: | Line 286: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
* | *在 SQL insert 时,必需给字段加引号,但不包括要存储在 double 或 real 类型字段中的金额数字。浮点数字上的引号有时会导致其存储了不同的值。例如,如果字段类型为 double(24,8),则插入412.62时实际上是将值412.61999512(由于隐式的字符串 - 数字转换)存储到数据库中。只有PHP可以看到412.61999512。其他工具将看到412.62,这使其看上去没有问题。但PHP是正确的,数据库中确实存在错误的值。通过删除数字上的引号,就不会出现此问题。 | ||
示例: | |||
<syntaxhighlight lang="sql"> | <syntaxhighlight lang="sql"> | ||
Good: INSERT INTO table_1 (field_txt, field_num) VALUES ('txt', 412.62) | Good: INSERT INTO table_1 (field_txt, field_num) VALUES ('txt', 412.62) | ||
| Line 292: | Line 295: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
请注意,浮点数的问题是普遍性的,不仅是在数据库访问上,而且在处理实数时,所有语言都存在浮点数问题。因此,一旦受到影响,就必须使用 price2num 函数清除浮点问题。根据需要,第二个参数设置为:“MU”(如果是单价)、“MT”(如果是总价)或“MS”(其他情况),具体取决于数字的使用情况。另请参阅下面的“实数、金额和计算”一章。 | |||
* | *SQL命令中不允许使用SQL日期函数NOW、SYSDATE、DATEDIFF。如果可能的话,还必须避免使用MONTH、YEAR。如果必须在字段中使用当前日期,则该值必须来自PHP,例如通过 dol_now() 函数,而不是来自数据库引擎。原因如下: | ||
**better portability of code | |||
**better management of TimeZone (reference timezone is the PHP timezone and timezone of database may differs so all dates functions must be on PHP side). | |||
**better performance (see example and final comment) For | |||
For example, don't do: | For example, don't do: | ||
edits