EAV - 如果行不存在,则添加具有空值的行

时间:2015-07-01 06:12:44

标签: mysql

我有下表在EAV模型中存储数据:

+-------------+---------+------+-----+---------+-------+
| Field       | Type    | Null | Key | Default | Extra |
+-------------+---------+------+-----+---------+-------+
| user_id     | int(11) | NO   | MUL | NULL    |       |
| question_id | int(11) | NO   | MUL | NULL    |       |
| answer      | blob    | YES  |     | NULL    |       |
+-------------+---------+------+-----+---------+-------+

使用表格来保存不同类型的问题:

+----------+---------+------+-----+---------+----------------+
| Field    | Type    | Null | Key | Default | Extra          |
+----------+---------+------+-----+---------+----------------+
| id       | int(11) | NO   | PRI | NULL    | auto_increment |
| question | blob    | YES  |     | NULL    |                |
+----------+---------+------+-----+---------+----------------+

以及用户表:

+------------------+--------------+------+-----+---------+----------------+
| Field            | Type         | Null | Key | Default | Extra          |
+------------------+--------------+------+-----+---------+----------------+
| id               | int(11)      | NO   | PRI | NULL    | auto_increment |
| user_name        | varchar(128) | YES  |     | NULL    |                |
+------------------+--------------+------+-----+---------+----------------+

如何为每个用户当前没有行的answer插入question_id的空值来编写查询?

例如,如果我有question_id s 1,2,3,4并且我的表存储数据如下:

+--------------+---------------+--------+
| user_id      | question_id   | answer |
+--------------+---------+-----+--------+
| 1            | 1             | example|
| 1            | 3             | example|
| 1            | 4             | example|
+--------------+---------+-----+--------+

我想插入一行如下:

+--------------+---------------+--------+
| user_id      | question_id   | answer |
+--------------+---------+-----+--------+
| 1            | 2             | NULL   |
+--------------+---------+-----+--------+

我试过这样的事情:

INSERT INTO profile_answers
(
    user_id,
    question_id,
    answer
)

SELECT
    id,
    profile_answers.question_id,
    null
FROM users
LEFT JOIN profile_answers ON profile_answers.user_id = users.id
WHERE NOT EXISTS (
    SELECT answer 
    FROM profile_answers 
    WHERE user_id = id
    AND question_id IN (
        SELECT GROUP_CONCAT(id SEPARATOR ',') FROM profile_questions
    )
)

但我最终插入question id为0的行。

1 个答案:

答案 0 :(得分:1)

我已经考虑过这个问题了,但是我找不到比在用户和问题之间使用笛卡尔积更好以及过滤子查询更好的事情:

SELECT u.id, q.id
FROM users u,
questions q
WHERE NOT EXISTS(
  SELECT *
  FROM profile_answers a
  WHERE a.question_id = q.id AND a.user_id = u.id
);

Demo