【问题标题】:How to select and insert into new table without duplicate value?如何选择并插入没有重复值的新表?
【发布时间】:2011-08-25 08:08:05
【问题描述】:

我有两张桌子。两个表有相同的字段,两个表有一些数据。现在我想在table1中选择数据并将数据插入到table2中。但我在两者之间使用,所以我很困惑。请帮助我...将数据插入到 table2 中,没有重复值。

INSERT INTO table2 
  (`student_id`, `studentname`, `Regno`, `class`, `date`, `session`
   , `status`, `teacher_id`) 
  SELECT * FROM table1, table2 
  WHERE table1.date <> table2.date
    BETWEEN '2011-01-01'
    AND '2011-05-19' AND table1.class = 'AAA'

【问题讨论】:

  • table2有主键吗?你如何定义重复?所有列都是相同的还是只是第一列……等等?
  • 我希望 student_id 成为 PK(或者可能是组合 (student_id + teacher_id)

标签: mysql


【解决方案1】:

您正在对不等式进行交叉连接,这将生成大量(重复)行。
相反,您应该对相等性执行 LEFT JOIN 并过滤掉 null 行。

我会把它改写成:

INSERT INTO table2 
  (`student_id`, `studentname`, `Regno`, `class`, `date`, `session`
   , `status`, `teacher_id`) 
SELECT t1.* FROM table1 t1
LEFT JOIN table2 t2 ON (t1.student_id = t2.student_id)
WHERE t1.`date` BETWEEN '2011-01-01' AND '2011-05-19' 
AND t1.`class` = 'AAA'
AND t2.student_id IS NULL 

这里student_id 是 t1 和 t2 的主键。如果 PK 是 (student_id + teacher_id) 那么查询变成:

INSERT INTO table2 
  (`student_id`, `studentname`, `Regno`, `class`, `date`, `session`
   , `status`, `teacher_id`) 
SELECT t1.* FROM table1 t1
LEFT JOIN table2 t2 ON (t1.student_id = t2.student_id 
                        AND t1.teacher_id = t2.teacher_id)
WHERE t1.`date` BETWEEN '2011-01-01' AND '2011-05-19' 
AND t1.`class` = 'AAA'
AND t2.student_id IS NULL  /*<<-- this stays the same provided student_id is  
                             <<-- defined as `NOT NULL` */

这是它的工作原理。
首先我们选择(t1.student_id = t2.student_id);的所有行。这会排列 t1 和 t2 中的所有匹配行。
因为它是左连接,所以在 t1 中但不在 t2 中的行将在 t2 列中具有 null 值。
通过只允许t2.student_id IS NULL 的行,我们只从 t1 中选择在 t2 中没有匹配行的行。

【讨论】:

    猜你喜欢
    • 2019-10-20
    • 2013-05-06
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 2017-11-23
    • 2016-09-17
    相关资源
    最近更新 更多