当使用AS表达式时,MySQL设置数据类型

时间:2017-04-23 14:33:13

标签: mysql types casting

我需要将数据类型设置为字段,但我无法完成此操作:

SELECT fname,lname,tname,games,
IFNULL((ib+iib+iiib+hr),0) AS h int (6), [does't work]
IFNULL((a+b+c)),0.000) AS ops decimal (6,3) [does't work]
FROM players,stats,teams
WHERE players.playerID = stats.sid AND players.club=teams.tid
ORDER BY obp DESC

3 个答案:

答案 0 :(得分:1)

预先投射该值:

SELECT fname, lname, tname, games,
       CAST(COALESCE(ib+iib+iiib+hr, 0) as signed) AS h, 
       CAST(COALESCE(a+b+c, 0.000)  as decimal(6, 3)) AS ops 
FROM players p JOIN
     stats s
     ON p.playerID = s.sid JOIN
     teams t
     ON p.club = t.tid
ORDER BY obp DESC;

我不认为cast() / convert()中允许整数的长度参数。

注意:

  • 从不FROM子句中使用逗号。 始终使用明确的JOIN语法。
  • 当您的查询引用多个表时,请使用表别名和限定列名始终
  • 我更喜欢COALESCE()IFNULL()因为COALESCE()是标准SQL。
  • 我对此加入条件非常怀疑:p.playerID = s.sid

答案 1 :(得分:0)

你可以使用COALESCE函数是MySQL。

示例:

SELECT COALESCE ((ib+iib+iiib+hr),0) AS h,  COALESCE ((a+b+c),0.000) AS ops 
FROM players,stats,teams WHERE players.playerID = stats.sid 
AND players.club=teams.tid ORDER BY obp DESC;

因此,您的查询(假设列名称可以具有正确的值,不再对任何数据类型进行类型转换)可能如下所示。

angular.js:14525 
    TypeError: EmpApi.getEmployees(...).success is not a function
    at getEmployees (demo.js:146)
    at new <anonymous> (demo.js:144)
    at Object.instantiate (angular.js:5018)
    at $controller (angular.js:10881)
    at Object.link (angular-route.js:1214)
    at angular.js:1346
    at invokeLinkFn (angular.js:10426)
    at nodeLinkFn (angular.js:9815)
    at compositeLinkFn (angular.js:9055)
    at publicLinkFn (angular.js:8920) "<div ng-view="" class="ng-scope">

试试这个,在没有数据的情况下,我刚刚为您提供了一个示例查询。

答案 2 :(得分:0)

嗨,这只是一个简单的MySQL连接来管理我的队友的棒球统计数据。

SELECT fname,lname,tname,games,
CAST(coalesce(ib+iib+iiib+hr,0) as signed) AS h,r,
CAST(coalesce(ib+iib+iiib+hr+so+fc+o,0) as signed) AS 
ab1,iib,iiib,hr,rbi,bb,
CAST(coalesce((ib*1)+(iib*2)+(iiib*3)+(hr*4),0) as signed) AS tb1,so,sb,
CAST(coalesce(((ib+iib+iiib+hr)+bb+hp)/(((ib+iib+iiib+hr)+so+fc+o)+bb+sf+hp)
,0.000) as decimal(6,3)) AS obp,
CAST(coalesce(((ib*1)+(iib*2)+(iiib*3)+
(hr*4))/((ib+iib+iiib+hr)+so+fc+o),0.000) as decimal(6,3)) AS slg,
CAST(coalesce((ib+iib+iiib+hr)/(((ib+iib+iiib+hr)+so+fc+o)),0.000) as 
decimal(6,3)) AS avg,
CAST(coalesce((((ib+iib+iiib+hr)+bb+hp)/(((ib+iib+iiib+hr)+so+fc+o)
+bb+sf+hp))+(((ib*1)+(iib*2)+(iiib*3)+
(hr*4))/((ib+iib+iiib+hr)+so+fc+o)),0.000) as decimal(6,3)) AS ops
FROM players p JOIN
 stats s
 ON p.playerID = s.sid JOIN
 teams t
 ON p.club=t.tid
ORDER BY obp DESC

完全正是我想要的!