我正在尝试显示值,直到MYSQL和PHP中的第一个空格为止。例如,
1 items from 29
100 items from 10
在第一个示例中,我只想显示数字1,在第二个示例中,我只想显示数字100,依此类推。这是我的代码,
$ordering = "SELECT t.id, t.cart_id, t.full_name, t.description, t.txn_date, t.grand_total, c.paid, c.shipped
FROM transactions t
LEFT JOIN cart c ON t.cart_id = c.id
WHERE c.paid = 1 AND c.shipped = 0
ORDER BY t.txn_date
现在,我要用显示的代码替换t.description
,直到第一个空格为止。我在互联网上搜索并找到了代码:
SELECT REVERSE(RIGHT(REVERSE(YourColumn), LEN(YourColumn) - CHARINDEX(' ', REVERSE(YourColumn))))
因此,我将t.description
替换为:
$ordering = "SELECT t.id, t.cart_id, t.full_name, t.REVERSE(RIGHT(REVERSE(description), LEN(description) - CHARINDEX(' ', REVERSE(description)))), t.txn_date, t.grand_total, c.paid, c.shipped
FROM transactions t
LEFT JOIN cart c ON t.cart_id = c.id
WHERE c.paid = 1 AND c.shipped = 0
ORDER BY t.txn_date
是吗?最好的方法是什么?
答案 0 :(得分:1)
对于MySQL,最简单的方法是使用SUBSTRING_INDEX
,例如
SELECT SUBSTRING_INDEX('100 items from 10', ' ', 1)
在第三个参数为正数(count
,在本例中为1)下,它返回第二个参数(在本例中为空格)在count
出现时的所有内容。因此,此调用将所有内容返回到第一个空格的左侧:
100
在查询中您将写
$ordering = "SELECT t.id, t.cart_id, t.full_name, SUBSTRING_INDEX(t.description, ' ', 1) AS description, t.txn_date, t.grand_total, c.paid, c.shipped
FROM transactions t
LEFT JOIN cart c ON t.cart_id = c.id
WHERE c.paid = 1 AND c.shipped = 0
ORDER BY t.txn_date