简体   繁体   English

一对多部分关联

[英]One to many partial association

I have an association called Includes between Parkings and Cars .我有一个名为Includes between Parkings and Cars的关联。

This is a one-to-many association that is partial both sides, because a parking can contain zero or more cars and a car can be contained by zero or one parking.这是一个对双方都是局部的一对多关联,因为一个停车场可以包含零个或多个汽车,而一个汽车可以包含零个或一个停车场。

I'd add a FOREIGN KEY related to a parking in the Cars table, but it's not true that a car is always inside a parking.我会在 Cars 表中添加与停车场相关的外FOREIGN KEY ,但汽车总是在停车场内并不正确。

How can this situation be managed?如何管理这种情况?

So, the car has a column saying where it is currently parked.所以,这辆车有一个栏目说明它目前停在哪里。 Or NULL if it is roaming the roads?或者NULL如果它在路上漫游?

And the parking lot (car park) can have lots of cars?停车场(停车场)可以有很多车吗? But it needs no column(s) to indicate such.但它不需要任何列来表明这一点。 The information can be had by a JOIN with the other table.该信息可以通过与另一个表的JOIN获得。

A FOREIGN KEY is 2 things:FOREIGN KEY是两件事:

  • An integrity check.完整性检查。 You wan't want a car parked in a nonexistent lot .你不希望car停在不存在的lot
  • An INDEX to make the above JOIN more efficient.使上述JOIN更高效的INDEX

We can't judge the indexes needed without seeing the SELECTs (and other queries).如果不查看SELECTs (和其他查询),我们就无法判断所需的索引。

To find all the cars in one lot:要在一个批次中找到所有汽车:

SELECT *
    FROM cars
    WHERE lot = 123 

That needs INDEX(lot) (or the FK) in cars .这需要cars中的INDEX(lot) (或 FK)。

To find where one car is:要查找一辆车的位置:

SELECT lot FROM cars WHERE id = 456;

Presumable cars has PRIMARY KEY(id) .推测的carsPRIMARY KEY(id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM