【问题标题】:SQL - JOIN statement creating duplicate entriesSQL - JOIN 语句创建重复条目
【发布时间】:2020-08-12 06:32:31
【问题描述】:

我是 SQL 新手,遇到了麻烦。

我有 3 张桌子:

CREATE TABLE indexCodes 
{
   (indexNum VARCHAR(5) PRIMARY KEY, 
   courseString VARCHAR(10), 
   title VARCHAR(20)
}

CREATE TABLE userid
{
     (id  INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
     email VARCHAR(255) NOT NULL, 
     password VARCHAR(255) NOT NULL)
}

    CREATE TABLE snipes
{ 
      (snipeNumber  INT NOT NULL PRIMARY KEY AUTO_INCREMENT), 
       FOREIGN KEY indexNum REFERENCES indexcodes(indexNum),
       FOREIGN KEY userID REFERENCES userid(id)
}

使用 JOIN 语句

SELECT  userid.id, userID.email, snipes.indexNum, indexcodes.courseString, == indexcodes.title
FROM userid JOIN
     snipes JOIN
     indexcodes ON indexcodes.indexNum = snipes.indexNum 

我遇到了重复的条目。 例如,基于一个用户插入的索引代码显示所有用户的索引

【问题讨论】:

  • 我遇到了重复的条目。当该行中所有列的值相同时,重复的行。如果至少一列中的值不同,则这些行不重复。如果输出中存在重复项,则至少其中一个表本身包含重复的行。

标签: mysql sql database foreign-keys primary-key


【解决方案1】:

尝试使用这两个选项

  1. GROUP BY 子句

    SELECT userid.id, userID.email, snipes.indexNum, indexcodes.courseString, == indexcodes.title FROM userid JOIN snipes 加入 indexcodes ON indexcodes.indexNum = snipes.indexNum GROUP BY userid.id

  2. 不同的

    SELECT DISTINCT userid.id, userID.email, snipes.indexNum, indexcodes.courseString, == indexcodes.title FROM userid JOIN snipes 加入 indexcodes ON indexcodes.indexNum = snipes.indexNum

【讨论】:

    【解决方案2】:

    MySQL 是唯一支持JOIN 且没有对应ON 子句的数据库。它真的应该返回一个错误!

    您缺少JOIN 条件:

    SELECT userid.id, userID.email, snipes.indexNum, indexcodes.courseString, == indexcodes.title
    FROM user
         snipes
         ON snipes.userid = user.id JOIN
         indexcodes
         ON indexcodes.indexNum = snipes.indexNum ;
    

    【讨论】:

      猜你喜欢
      • 2014-12-18
      • 2021-01-08
      • 2012-10-02
      • 1970-01-01
      • 2010-09-10
      • 1970-01-01
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多