繁体   English   中英

MySQL内部连接根据值的多个表

[英]Mysql inner join with multiple tables according to a value

我必须创建一个待售的真实状态数据库。 问题在于物业的种类:如果我有一所房子,我会有一种描述,但是如果它只是一块土地,则描述不需要包括浴室的数量,区域,前范围等。

因此,我制作了一个表,其中包含有关元素(imoveis),地址,价格等的常规数据。然后,我创建了元素类别(imoveis_categs)。 我做了5个类别,对于每个类别,都会有一个带有该类型特定功能的表(例如:imoveis_descr2)。

要输入数据很容易,但是要列出我的数据,我将需要执行查询选择以根据一些过滤器找到那些元素。 用PHP将很容易解决,但是我想知道大量数据和用户请求的性能。 可以通过SQL命令更好地解决它。 但是mySQL不是我的领域,我想这样的事情就开始了...

 SELECT * FROM imoveis INNER JOIN imoveis_descr(imoveis.categ) ...

imoveis的“ categ”字段指向正确的描述表。 可以做这样的事情吗? 还有另一种更合适或更有效的方法吗?

编辑:我试图用一个例子来阐明...编辑2:我更正了这个例子,列“房间”将是相同的。 该字段不是排他性的,公寓和房屋类别都有房间数。

Table imoveis
id  categ   title            price       address ...
1   2       The House        $ 1000000   Somestreet 77
2   1       An Appartment    $ 500000    Somewhere 11
3   4       A Land           $ 250000    Nowhere 33

Table imoveis_descr1
idImovel    rooms   area    floor   ...
2           2       70      5

Table imoveis_descr2
idImovel    rooms fieldArea   constrArea ...
1           3      120        80

Table imoveis_descr4
idImovel    area    width   height ...
3           2640    22      120

Result
id   categ    title       price     address   rooms fieldArea  constrArea    area    floor        area   width  height
1      2     The House    $ 1000000 Somestreet 77   3   120 80  null    null    null    null    null
2   1   An Appartment   $ 500000    Somewhere 11    2   null    null    70  5   null    null    null
3   4   A Land  $ 250000    Nowhere 33  null    null    null    null    null    2640    22  120

您的某些字段名称在结果中重复(例如“房间”),将这些字段与COALESCE合并会更好(因为它们看起来互斥)?

由于您引用的表是互斥的,因此使用INNER JOIN永远不会获得所需的结果,而需要OUTER JOIN

SELECT
      i.id,
      i.categ,
      i.title,
      i.price,
      i.address,
      COALESCE(i1.rooms, i2.rooms) AS rooms,
      i2.fieldArea,
      i2.constrArea
      COALESCE(i1.area, i3.area, ...) AS area,
      ...
FROM  imoveis AS i
      LEFT OUTER JOIN imoveis_descr1 AS i1 ON i1.idImovel = i.id
      LEFT OUTER JOIN imoveis_descr2 AS i2 ON i2.idImovel = i.id
      LEFT OUTER JOIN imoveis_descr3 AS i3 ON i3.idImovel = i.id
      ...

暂无
暂无

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

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