如何在MySql中选择ENUM类型的值个数?

发布于 2024-12-03 15:02:58 字数 238 浏览 4 评论 0 原文

我需要从下表中选择一行,但问题是 $row['city'] 中的值是该值的文本表示,而我需要它的编号(Toronto = 2)。 (与我们 INSERT INTO 时相同,我们使用值数字而不是文本)

请求表结构:

req_id INT
uname  VARCHAR(30)
city   ENUM('New York', 'Toronto', 'Las Vegas')

I need to select a row from table below, but the problem is the value in $row['city'] is the textual represent of the value, and i need its number(Toronto = 2). (Same as when we INSERT INTO, and we use value number instead of text)

Requests Table Structure:

req_id INT
uname  VARCHAR(30)
city   ENUM('New York', 'Toronto', 'Las Vegas')

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

明媚如初 2024-12-10 15:02:58

您只需要从 city 转换为数字上下文“nofollow noreferrer”>精美手册

如果您在数字上下文中检索 ENUM 值,则会返回该列值的索引。例如,您可以从 ENUM 列中检索数值,如下所示:

mysql>从 tbl_name 中选择 enum_col+0;

所以您想要这样的事情:

select req_id, city+0
from your_table
where city = 'Toronto'

顺便说一句,您可以使用字符串或整数插入 enum表示。

You just need to force your city into a numeric context, from the fine manual:

If you retrieve an ENUM value in a numeric context, the column value's index is returned. For example, you can retrieve numeric values from an ENUM column like this:

mysql> SELECT enum_col+0 FROM tbl_name;

So you want this sort of thing:

select req_id, city+0
from your_table
where city = 'Toronto'

BTW, you can insert an enum using either the string or integer representation.

心病无药医 2024-12-10 15:02:58

您可以使用CAST函数。 文档没有提到这个特定的用例,但它按预期工作。我更喜欢它,因为它看起来优雅而清晰:

SELECT CAST(city AS UNSIGNED) FROM your_table;

You can use the CAST function. The documentation doesn't mention this specific use case, but it works as expected. I prefer it because it looks elegant and clear:

SELECT CAST(city AS UNSIGNED) FROM your_table;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文