doubian19900911 2013-03-13 09:30
浏览 134
已采纳

mysql自定义全局定义变量

In my database design, I tend to store some variable that is meant to be acting as a ROLE or TYPE as SMALLINT. For example :

CREATE TABLE `house` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `type` smallint(11) NOT NULL,

And in php, I do

define('HOUSE_SMALL_TYPE', '0');
define('HOUSE_MEDIUM_TYPE', '1');

So in php, in SELECT queries I do :

$this->db->query("SELECT * FROM house  
                    WHERE type=?;", HOUSE_SMALL_TYPE);

My questions are :

  1. In the php part, is there is a better way to do this ?
  2. In the mysql itself, does mysql also has global define functionality (like the define in php) ?

I also want to do kind of

SELECT * FROM house  WHERE type = HOUSE_SMALL_TYPE

in mysql query.
My purpose is that when I do SELECT in mysql, no way I'm going to keep mapping the value 0,1,2 with its real meaning. Just convineance for viewing the tables values, without changing the structure table and fields.

  • 写回答

4条回答 默认 最新

  • douweilei2307 2013-03-13 11:39
    关注

    I suggest using MySQL variables:

    SET HOUSE_SMALL_TYPE = 0;
    SET HOUSE_MEDIUM_TYPE = 1;
    

    Then, in your queries you may use these variables:

    SELECT * FROM house  WHERE type = @HOUSE_SMALL_TYPE;
    

    This method defines session variables:

    If you change a session system variable, the value remains in effect until your session ends or until you change the variable to a different value. The change is not visible to other clients.

    If you want to define global MySQL variables (available to all sessions):

    SET GLOBAL HOUSE_SMALL_TYPE = 0;
    SET GLOBAL HOUSE_MEDIUM_TYPE = 1;
    

    To indicate explicitly that a variable is a global variable, precede its name by GLOBAL or @@global.. The SUPER privilege is required to set global variables.

    Documentation:
    SET statement
    Using system variables
    User-defined variables

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀