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

时间:2022-11-20 16:26:04

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)

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

Requests Table Structure:

请求表结构:

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

2 个解决方案

#1


13  

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:

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

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.

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

#2


2  

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:

您可以使用CAST功能。该文档未提及此特定用例,但它按预期工作。我更喜欢它,因为它看起来优雅而清晰:

SELECT CAST(city AS UNSIGNED) FROM your_table;

#1


13  

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:

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

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.

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

#2


2  

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:

您可以使用CAST功能。该文档未提及此特定用例,但它按预期工作。我更喜欢它,因为它看起来优雅而清晰:

SELECT CAST(city AS UNSIGNED) FROM your_table;