如何从索引中获取枚举元素

时间:2009-09-09 05:37:52

标签: mysql sql enums indexing

我有一个选择,其中我做了“分组依据”。其中一列是枚举,我想为每个组选择最大值(即枚举中索引最大的值)。我能做到

select MAX(enum_column+0) as enum_index 

获取组中最大的索引,但是如何将枚举索引转回枚举项?


实施例: 假设我有一个有三列的“士兵”表:

"id" - soldier's ID
"name" is the soldier's first name (a varchar field).
"rank" is the soldier's rank, and it is an enum: 
{'private','sergent'...,'lieutenant' etc.} 

现在假设我想为每个名字找到具有该名称的人的最高级别。 我能做到:

select MAX(rank+0) as enum_index,name from soldiers group by name

但是这会给我枚举字段中max元素的索引,而不是元素的名称。它会给我:

1 | john
2 | bob

我想要的地方

'private' | john
'sergent' | bob 

如何达到预期效果?

2 个答案:

答案 0 :(得分:2)

运行以下

CREATE TABLE ranks
SELECT DISTINCT rank+0 as id, CONCAT('',rank) as rank
FROM soldiers

然后用士兵表加入数据。请注意,它只会为您提供实际使用的排名。

答案 1 :(得分:0)

0private

concat会生成1sergeantMAX等项目;这些将在获取substr时按字符串排序。在这种情况下,这与按枚举顺序排序相同。最后,substr删除了初始数字。

如果您的枚举中有超过10个项目,则必须使用前导数字格式化数值,并删除 func displayLocationInfo(placemark:CLLocationCoordinate2D) ->String{ self.locationManager.stopUpdatingLocation() originTextField.text = ("locations = \(placemark.latitude) \(placemark.longitude)") } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { var locValue:CLLocationCoordinate2D = manager.location.coordinate displayLocationInfo(locValue) } @IBAction func currentLocation(sender: AnyObject) { self.locationManager.requestAlwaysAuthorization() // For use in foreground self.locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters locationManager.startUpdatingLocation() } } 来电中的其他数字。