SELECT SET()中的第一个元素应该是怎么做?

huangapple go评论46阅读模式
英文:

How do I SELECT the first element in a SET()?

问题

我有一个带有 SET 字段的表:

CREATE TABLE `test` (`testset` set('one','two'))

有一些记录:

SELECT * FROM test;
+---------+
| testset |
+---------+
| one     |
| two     |
| one,two |
+---------+

如何选择每个记录的第一个元素?在这种情况下,可以这样做:

SELECT SUBSTRING_INDEX(testset, ',', 1) AS testset FROM test;
+---------+
| testset |
+---------+
| one     |
| two     |
| one     |
+---------+

当然,testset[0] 不起作用(我已经尝试过了),但我可以这样做。

英文:

I have a table with a SET field:

CREATE TABLE `test` (`testset` set('one','two') )

with a few records:

SELECT * FROM test;
+---------+
| testset |
+---------+
| one     |
| two     |
| one,two |
+---------+

How can I SELECT the first element of each record? So in this case, that would be

SELECT testset[0] FROM test;
+---------+
| testset |
+---------+
| one     |
| two     |
| one     |
+---------+

of course, testset[0] doesn't work (I tried), but how could I do this?

答案1

得分: 0

  • MySQL的SET被实现为一个有序列表。
  • 它以整数形式存储,其中最低位表示SET声明中的第一个项目。
  • INSERTSELECT都会将列的值视为逗号分隔列表。
  • 实现具有顺序性,但概念本身没有。
  • 所以... SUBSTRING_INDEX就是答案:

要查看它,请在您的表上尝试以下操作:

SELECT testset, SUBSTRING(testset, ',', 1) FROM test
    ORDER BY RAND() LIMIT 11;

请注意:这是原文的中文翻译。如果您需要任何进一步的帮助,请告诉我。

英文:
  • A MySQL SET is implemented as an ordered list.
  • It is stored in an integer, with the bottom bit representing the first item in the SET declaration.
  • INSERTing and SELECTing both act as if the value of the column as a commalist.
  • The implementation has ordering, the concept does not.
  • So... SUBSTRING_INDEX is the answer:

To see it, try this on your table:

SELECT testset, SUBSTRING(testset, ',', 1) FROM test
    ORDER BY RAND()  LIMIT 11;

huangapple
  • 本文由 发表于 2023年5月25日 19:41:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76331879.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定