我有一个Daily_account
表:
customer_id account_id current_balance
1 D1 200
2 d2 300
3 d10 400
4 d100 500
5 d101 600
现在我有一个问题:
select customer_id,account_id,current_balance
from daily_account
where account_id between 'D1' and'D100'
它给出了D1,D10,D100的账号no的输出,但是我希望得到每个no的输出。 如何获得介于D1和d100之间的每个帐户的输出?
答案 0 :(得分:1)
select customer_id, account_id,current_balance from daily_account
where cast(right(Account_id,(length(account_id)-1)) AS unsigned)
between '1' and'100'
答案 1 :(得分:1)
上面代码段中的between语句使用字符串,这与数字排序不同。
如果account_id始终以'D'开头,我们可以删除它并将其转换为数字:
SELECT *
, REPLACE(account_id, 'd','0') // just replace
, CAST( REPLACE(account_id, 'd','0') as int) // now convert to int
FROM daily_account
并在两者之间使用它,像这样使用
SELECT customer_id,account_id,current_balance
FROM daily_account
WHERE
CAST( REPLACE(account_id, 'd','0') as int) between 1 and 100
答案 2 :(得分:1)
如果一切都以一个字符开头,你可以这样做:
SELECT * FROM (
SELECT customer_id
, CAST(REPLACE(account_id,'d','') AS int) account_id
, current_balance
FROM daily_account) tbl
WHERE account_id between '1' and'100'
答案 3 :(得分:1)
一个技巧是删除account_id中的非数字,如下所示:
SELECT * FROM Daily_account WHERE CAST(REPLACE(account_id,'D','') AS INT) BETWEEN 1 AND 10
答案 4 :(得分:1)
select customer_id,account_id,current_balance
from daily_account
where CAST(replace(account_id, 'D', '') as int) between 1 and 100
答案 5 :(得分:0)
您的回答似乎暗示您希望解决方案能够使用各种前缀,而不仅仅是'D'
。如果是这种情况,请考虑以下替代方案:
SELECT customer_id, account_id, current_balance
FROM daily_account
WHERE STUFF(account_id, 1, 1, '') between 1 and 100
;
以上是SQL Server,但由于您的回答似乎暗示您使用的是MySQL,因此这里有一个MySQL等价物:
SELECT customer_id, account_id, current_balance
FROM daily_account
WHERE INSERT(account_id, 1, 1, '') between 1 and 100
;