【问题标题】:MySQL: any way to have a column defaults to auto-increment (or copy from an auto-increment field) but still allow other values to be inserted?MySQL:任何方式让列默认为自动增量(或从自动增量字段复制)但仍允许插入其他值?
【发布时间】:2011-08-04 02:52:58
【问题描述】:

我正在建立一个问答网站。我想将问题和答案都存储在同一个表中:

CREATE TABLE Q_n_A (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    question_id INT NOT NULL,
    # type indicates whether the record is a question (1) or an answer (0)
    type BOOL,
    title VARCHAR(80),
    body VARCHAR(5000)
);

当我插入一个新问题时,这个新问题没有question_id 的值。因此,我想使用 id 的 auto_incremented 值作为 question_id 的值。所以在这种情况下,我希望 question_id 默认为 AUTO_INCREMENT 或从 id 复制。

当我插入现有问题的答案时,我已经知道该答案的 question_id 是什么。因此,我想在插入时为 question_id 指定一个值。

有没有办法在这里做我想做的事:默认question_idAUTO_INCREMENT(或从AUTO_INCREMENT 字段id 复制)但仍然允许指定question_id 的非默认值?

谢谢。

【问题讨论】:

标签: mysql database-design auto-increment


【解决方案1】:
CREATE TABLE Q_n_A (
overall_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
parent_id INT default '0',
title VARCHAR(80),
body VARCHAR(5000)
);

现在当有人问简单地插入没有 parent_id,导致它有 parent_id = 0 当有人回答时,通过 $_POST 数据或您的表单设置将 ovverall_id 插入 parent_id。

使查询给定问题的正确答案变得容易

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2015-03-11
    相关资源
    最近更新 更多