SQL查询用外国钥匙的任何命令返回重复

发布于 2025-01-18 16:21:10 字数 505 浏览 0 评论 0原文

其他答案似乎正在使用加入,如果我错了,如果您有外键,您不需要使用哪个答案?如果您确实需要使用加入,您会介意显示与此作用的功能吗?

CREATE TABLE Dogs (
DogID int NOT NULL,
DogSize int NOT NULL,
fName VARCHAR(255),
ID int,
PRIMARY KEY (DogID),

CREATE TABLE Owners (
ID int NOT NULL,
Fname VARCHAR(255) NOT NULL,
Lname VARCHAR(255),
Area VARCHAR(255) NOT NULL,
Pay INT NOT NULL,
Extra INT,
PRIMARY KEY (ID)
FOREIGN KEY (ID) REFERENCES Owners(ID)

“

Other answers seem to be using JOIN, which correct me if I'm wrong you don't need to use if you have a foreign key? If you do need to use JOIN would you mind showing what would work with this?

CREATE TABLE Dogs (
DogID int NOT NULL,
DogSize int NOT NULL,
fName VARCHAR(255),
ID int,
PRIMARY KEY (DogID),

CREATE TABLE Owners (
ID int NOT NULL,
Fname VARCHAR(255) NOT NULL,
Lname VARCHAR(255),
Area VARCHAR(255) NOT NULL,
Pay INT NOT NULL,
Extra INT,
PRIMARY KEY (ID)
FOREIGN KEY (ID) REFERENCES Owners(ID)

The result of a SELECT * query

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别把无礼当个性 2025-01-25 16:21:10

外键才能确保您的数据井井有条。进行查询时,它无济于事。当然,不使用加入并不是一件好事。

您的查询是一个老式的查询,出于许多原因,您不应该使用。相当于您所写的内容如下:

SELECT * FROM Dogs CROSS JOIN Owners

这称为笛卡尔产品,这意味着所有组合都会返回,因为您没有提供加入条件。我认为您不是因为您认为它会由外键自动提供。...但是它不起作用。您必须提供自己想要的东西。

现在解决下一个问题。您实际上没有连接。所有者上的外键不仅针对表本身,而且针对列本身。这是零有意义的。您可能想为每个主人分配一只狗吗? 应该有所有者上的另一列(不是主键一个),这将是dogs的外键:

[Dogid] INT,外键(Dogid)参考狗(ID)

这更好。不过,不是很好;它将将每个主人拥有的狗限制为一个或零。一个更好的主意是在狗中制作一个新的专栏,以引用所有者:

[lansalId] int,forefer键(handerID)参考所有者(id)

A foreign key is only there to make sure your data are well-organized. It does not help you "behind the scenes" when making queries. And it certainly doesn't make it good to not use joins.

Your query is an old-style query, which for many reasons you shouldn't use. The equivalent of what you wrote is the following:

SELECT * FROM Dogs CROSS JOIN Owners

This is called a cartesian product, which means all the combinations are returned, since you didn't provide a join condition. I assume you didn't because you thought it would be automatically provided by the foreign key....but it doesn't work that way. You have to provide what you want yourself.

Now for the next problem. You do not really have a connection. The foreign key on Owners is targeting not only the table itself, but actually the column itself. That makes zero sense. Did you maybe want to assign one dog to each owner? There should be another column on Owners (not the primary key one) that would be a foreign key to Dogs:

[DogID] int,FOREIGN KEY (DogID) REFERENCES Dogs(ID)

This is better. Still, not very good; it would limit the dogs owned by each owner to one or zero. A better idea would be to make a new column in Dogs that would reference the owner:

[OwnerID] int,FOREIGN KEY (OwnerID) REFERENCES Owners(ID)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文