gpt4 book ai didi

mysql - 将列值限制为预定义的字符串列表

转载 作者:行者123 更新时间:2023-11-29 02:55:06 26 4
gpt4 key购买 nike

我想在 mysql 中预定义列的可能值。

例如 Fruits 列可以有值 apple, orange, mango 作为单独的值,或者可以有像 apple,orange 这样的列表,苹果,芒果

eg:
juice fruites
---------------------
j1 'mango'
j2 'mango,apple'
j3 'apple,orange'
j4 'apple'
....etc

我可以找到 check constraintsEnum 来达到这个目的,有没有更好的方法来实现同样的目的?

因为将来我可能想在这个列表中添加更多元素,比如 grapes,所以我现在使用的方法一定很广泛。

所以请建议最好的方法,或者如果我必须使用 constraintEnum 哪个更好,就易于扩展而言。

最佳答案

I could find check constraints or Enum to serve this purpose is there any better way to accomplish the same?

是的,使用链接表规范化您的数据库:

 juice
id | name
1 j1
2 j2

fruit
id | name
1 mango
2 apple

juices_fruits
juice_id | fruit_id
1 1
2 1
2 2

使用适当的外键约束(juice_id 引用 juice.id 和 fruit_id 引用 fruit.id),您只能将“有效”水果插入 juices_fruits 表。此外,您可以对 juice_id、fruit_id 使用 unique_key 约束,以确保不会将水果添加两次到同一果汁中。

要查询这个,您可以使用 group_concat 来获取逗号分隔的列表:

SELECT j.name, GROUP_CONCAT(f.name) FROM
juice j
LEFT JOIN
juices_fruits jf
on
jf.juice_id = j.id
LEFT JOIN
fruit f
ON
jf.fruit_id = f.id
GROUP BY
j.id;

结果:

j1 | mango
j2 | mango,apple

关于mysql - 将列值限制为预定义的字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31470333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com