无法获得LEFT OUTER JOIN来处理交叉表

时间:2015-09-23 02:17:15

标签: mysql sql

我有2个查找和1个交叉表,如:

thing                  thing_feature                    feature
+----+-------------+   +----+----------+------------+   +----+-------------+
| id | name        |   | id | thing_id | feature_id |   | id | name        |
+----+-------------+   +----+----------+------------+   +----+-------------+
|  1 | Thing One   |   |  1 |        1 |          1 |   |  1 | Feature A   |
|  2 | Thing Two   |   |  2 |        2 |          1 |   |  2 | Feature B   |
|  3 | Thing Three |   |  3 |        2 |          2 |   |  3 | Feature C   |
|  4 | Thing Four  |   |  4 |        3 |          3 |   |  4 | Feature D   |
+----+-------------+   +----+----------+------------+   +----+-------------+

我无法弄清楚要生成的查询...

"Thing One", "Feature A"
"Thing Two", "Feature A"
"Thing Two", "Feature B"
"Thing Three", "Feature C"
"Thing Four", null

如果我停在交叉牌桌上,我可以把它包含在“东西4”中......

select
  thing.name,
  tf.id
from
  thing
  left outer join thing_feature tf on thing.id = tf.thing_id;

"Thing One", 1
"Thing Two", 1
"Thing Two", 2
"Thing Three", 3
"Thing Four", null

...但我无法弄清楚通过thing_feature.feature_id让查询“连接”到功能表的语法。我几乎工作的查询失去了无特征“Thing Four”。

select
  thing.id,
  thing.name,
  tf.id,
  feature.name
from
  thing
  left outer join thing_feature tf on thing.id = tf.thing_id,
  feature
where
  tf.feature_id = feature.id;

"Thing One", 1, "Feature 1"
"Thing Two", 1, "Feature 1"
"Thing Two", 2, "Feature 2"
"Thing Three", 3, "Feature 3"

也许我已经深入NoSQL很长时间了。这是MySQL,如果重要的话。

这里的帮助不大?我需要对查询进行哪些操作才能包含“Thing Four”行?

4 个答案:

答案 0 :(得分:2)

几乎那里。您只需再做一次左外连接,以确保将所有结果保留在左表中,并获得右侧的所有空值。

select
  thing.name,
  f.name
from
  thing
  left outer join thing_feature tf on thing.id = tf.thing_id
  left outer join feature f on tf.feature_id = f.id;

答案 1 :(得分:1)

SELECT 
    t.name tname, t.id, f.name as fname, f.id, tf.tid, tf.feature_id
FROM 
    thing as t
LEFT JOIN
    thing_feature as tf
ON
  t.id = tf.thing_id 
LEFT JOIN
  feature as f
ON 
  tf.feature_id = f.id

答案 2 :(得分:1)

您可以使用以下查询 -

SELECT th.name, ft.name 
FROM thing AS th 
LEFT JOIN thing_feature AS tf ON th.id=tf.thing_id 
LEFT JOIN feature AS ft ON ft.id=tf.feature_id 

首先从左表中获取所有行表示事物表,然后从右表中更新相应的行,如果右侧表中没有对应的值,那么它将置为NULL。

答案 3 :(得分:0)

我认为通过在功能表上使用RIGHT OUTER JOIN代替,应该解决您的问题并包含null。