简体   繁体   English

PHP / MySQL使用varchar作为ID

[英]PHP / MySQL using varchar as a sort of id

I have to create a database that contains some information about a few products and some SKU's, part of this is the product type and sub-type, having a total of 60-70 product types and 2-20 sub-types for each of them. 我必须创建一个数据库,其中包含有关一些产品和一些SKU的一些信息,其中一部分是产品类型和子类型,共有60-70个产品类型和2-20个子类型。

The part of SKU code that needs to be generated is in the form XXY, where XX is the product type and Y is the sub-type of it, for the type part it was easy to add a unique auto_increment field (since it will never go over 99) but for the sub-type part i need to use both numbers and letters in an order like 1-9-AZ. 需要生成的SKU代码部分的格式为XXY,其中XX是产品类型,Y是其子类型,对于类型部分,很容易添加唯一的auto_increment字段(因为它将永远不会超过99),但对于子类型部分,我需要同时使用数字和字母(例如1-9-AZ)。

What is the simplest way to achieve this ? 实现此目的的最简单方法是什么? I have some idea how to do it with javascript / json to check and retrieve the Y field but i got a feeling there must be an easier way with just using php/mysql for this. 我有一些想法如何使用javascript / json来检查和检索Y字段,但是我感觉必须使用php / mysql才能有一种更简单的方法。

Basically what i need is for php/mysql to generate a single-character "id subtype" from 1 to Z for each unique product type. 基本上,我需要的是php / mysql为每种唯一的产品类型生成一个从1到Z的单字符“ id子类型”。

I'm afraid you'll have to use Javascript or PHP (or anything you are using server side) to generate this char. 恐怕您将不得不使用Javascript或PHP(或您正在使用服务器端的任何东西)来生成此字符。 There's no builtin SQL function to do that. 没有内置的SQL函数可以执行此操作。 For your single-character id subtype you shouldn't use VARCHAR BUT CHAR(1) . 对于您的单字符id子类型,您不应使用VARCHAR BUT CHAR(1)

CHAR has a fixed length, therefore will take only 1 byte per character. CHAR具有固定长度,因此每个字符仅占用1个字节。 VARCHAR takes the same as CHAR + 2 bytes to hold length information. VARCHARCHAR + 2个字节相同,以保存长度信息。

Example: 例:

$characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; 
$char = strtoupper($characters[rand(0, strlen($characters) - 1)]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM