【问题标题】:What does it mean by "There is no primary key for this table, it may contain duplicates."?“此表没有主键,它可能包含重复项。”是什么意思?
【发布时间】:2022-11-07 03:56:31
【问题描述】:

我知道此表中没有唯一的一列或多列。 但是,这是否意味着不止一行具有完全相同的列?或者这是否仅意味着某些列可以具有重复值但表中没有完全相同的行? 另外,我一直使用与 cte as (select distinct (column1, column2 ...)" 来删除这些表中的重复行,然后再用主键连接其他表......我觉得这可能没有必要,但我是不确定。有人可以为我澄清一下吗?谢谢!

由于这个问题,我有这个问题:

Table: Prices

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| start_date    | date    |
| end_date      | date    |
| price         | int     |
+---------------+---------+
(product_id, start_date, end_date) is the primary key for this table.
Each row of this table indicates the price of the product_id in the period from start_date to end_date.
For each product_id there will be no two overlapping periods. That means there will be no two intersecting periods for the same product_id.
 

Table: UnitsSold

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| purchase_date | date    |
| units         | int     |
+---------------+---------+
There is no primary key for this table, it may contain duplicates.
Each row of this table indicates the date, units, and product_id of each product sold. 
 

Write an SQL query to find the average selling price for each product. average_price should be rounded to 2 decimal places.

Return the result table in any order.

为了答案,我写

select p.product_id, round(sum(units*price)/sum(units),2) as average_price
from prices p
join unitssold u on p.product_id = u.product_id and purchase_date between start_date and end_date group by p.product_id;

提交成功。但我想知道如果unitsold 表中有重复的行,答案是否仍然正确......因为重复的行也被计算了,对吗? screenshot of the leetcode problem

【问题讨论】:

  • 如果您没有主键,则可以有两行或多行完全相同。删除重复项的方式取决于您拥有的数据和您在做什么。您可以使用唯一键避免重复,或者您可以删除重复项,或者您可以使用 distinct 来获取列/行中的不同值。真的很宽
  • PRIMARY KEY 的存在仅保证 PK 表达式值的唯一性。如果没有 PK 但存在 UNIQUE KEY,则它保证 UK 表达式值的唯一性,但该表达式值为 NULL 的行除外。非唯一索引(和索引存在)不能保证任何事情。
  • 答案是否有帮助

标签: mysql duplicates


【解决方案1】:

关于您的情况,如果您没有唯一键(或主键)product_id那么可以有多个相同的行product_id.数据库引擎不会检查阻止这种情况发生。

如果你有一个唯一键product_id那么数据库将在尝试插入带有 a 的行时引发错误product_id如果这样的行已经存在。

【讨论】:

    猜你喜欢
    • 2019-11-14
    • 2022-01-12
    • 1970-01-01
    • 2023-04-10
    • 2020-04-22
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2014-10-06
    相关资源
    最近更新 更多