【问题标题】:Proper query or proper normalization: MySQL适当的查询或适当的规范化:MySQL
【发布时间】:2012-04-16 14:47:43
【问题描述】:

我要做的是访问表中的正确行,以便它返回正确的位置名称、地址等。地址返回正确,但有三个结果而不是一个。这些是我们的不同国际地点。

要么我的表没有正确规范化,要么我的查询写错了。我不知道是哪个。也许两者兼而有之。这是我的表格:

DEALERS TABLE: 

channel_partner_id    company
------------------    --------
626                   Company Inc.
626                   Company GmBH
626                   Company Ltd.

DEALERS_LOCATIONS TABLE:

channel_partner_id    location_id
------------------    -----------
626                   18
626                   19
626                   20

LOCATIONS TABLE:

location_id           address                name_url
----------            --------------------   -------
18                    1234 Anywhere St.      anywhere-st
19                    3245 Nowhere St.       nowhere-st
20                    90 Everywhere St.      everywhere-st

我想通过 name_url 加入他们。

这是我在 CodeIgniter/Active Record 中的查询(很容易翻译成标准 MySQL):

$this->db->where('l.name_url', $name_url);
$this->db->join('all_dealers_locations dl', 'dl.channel_partner_id = d.channel_partner_id', 'inner');
$this->db->join('all_locations l', 'l.location_id = dl.location_id', 'inner');
$row = $this->db->get('all_dealers d')->row();

但是我从中得到了三个结果。为什么,如果我使用 name_url 的 where 子句(它被正确传递到函数中)?这是我的加入类型吗?我尝试了左和外,但没有帮助。

我做错了什么?

【问题讨论】:

  • 在您拥有的示例数据中,所有 3 个经销商都有相同的合作伙伴 ID,该 ID 映射到所有 3 个位置。因此,无论您从哪个位置加入,您都将获得全部 3 个经销商 = 3 行。
  • 我知道,但我还需要能够查询所有位置?如果他们有唯一的 ID,那么我如何获取给定渠道合作伙伴的所有位置?
  • 您说您“想在 name_url 上加入他们”,但您的查询似乎没有这样做。 ???

标签: mysql codeigniter


【解决方案1】:

您的桌子有一些问题。

大红旗是dealers 有多个具有相同id 的行(这意味着channel_partner_id 不能是主键)。

这是一个问题,因为看起来dealers_locations 应该是一个交集表。实现这样一个表的标准方法是获取两个表的主键,在这种情况下是locationsdealers。由于dealer_locations 没有dealers 的主键,所以它不起作用。

下面是我将如何实现它:

create table dealers (
  channel_partner_id   int primary key,
  name                 varchar(30)
);

create table locations (
  location_id  int primary key,
  address      varchar(30),
  name_url     varchar(30)
);

create table dealer_locations (
  location_id int,
    foreign key (location_id) references locations(location_id),
  channel_partner_id int,
    foreign key (channel_partner_id) references dealers(channel_partner_id),
  primary key (location_id, channel_partner_id)
);

注意dealer_locations 的两部分主键。

【讨论】:

  • 谢谢,马特。这很棒。
猜你喜欢
  • 2017-03-21
  • 2015-10-28
  • 2014-05-20
  • 2013-08-21
  • 2016-11-08
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2012-08-17
相关资源
最近更新 更多