无论是使用左外连接还是右外连接,外连接似乎都不起作用:
SELECT * FROM `event_orchestra_musicians` eom
right outer join `orchestra_instruments` oi on eom.instrument_id = oi.oi_id
where event_id = 2
order by instrument_id
Orchestra_instruments包含具有唯一ID的不同乐器,即:
Event_Orchestra_Musicians是一个将音乐家加入乐器的查找表,即:
musician_id, instrument_id, event_id,
1 1 2
2 1 2
3 3 2
4 2 2
当我进行任何外部联接时,使用这些表中的数据,我会得到内部联接的结果(Piccolo不会显示为null musician_id,它根本不显示)。有什么我做错了吗?
编辑:
所以我做了一些吵架。问题似乎是因为events_orchestra_musicians表中有一条记录,event_id为5,instrument_id为7.如果删除该记录,则外连接起作用。我没有得到的是,如果那条记录在那里并且我使用where子句来查找event_id = 2,那么如果其中有一个记录,如果其event_id为5,那么如果其中有一个记录,其中有一个记录,那么为什么呢?
答案 0 :(得分:2)
试试这个:
select oi.oi_id, oi.instrument_name, eom.musician_id
from orchestra_instruments oi
left join event_orchestra_musicians eom on oi.oi_id = eom.instrument_id
where (eom.event_id = 2 or eom.event_id is null)
order by oi.oi_id
你必须使用orchestra_instruments作为基表,因为那是你想要所有记录的那个,即使没有音乐家存在。我无法想象在左连接上使用右连接的任何原因,并暗示外部。此外,您必须允许event_id为2或null,因为如果没有要加入的匹配记录,则不能为2。
答案 1 :(得分:1)
您在Event_Orchestra_Musicians
instrument_id=4
中没有任何记录,因此您在执行某项操作时需要检查来自null
的{{1}}值右外连接。
eom
答案 2 :(得分:0)
这是我的完整设置。也许你的结构有什么东西?
mysql> show columns from orchestra_instruments;
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| oi_id | int(11) | YES | | NULL | |
| oi_name | varchar(10) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
2 rows in set (0.01 sec)
mysql> show columns from event_orchestra_musicians;
+---------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+---------+------+-----+---------+-------+
| musician_id | int(11) | YES | | NULL | |
| instrument_id | int(11) | YES | | NULL | |
| event_id | int(11) | YES | | NULL | |
+---------------+---------+------+-----+---------+-------+
3 rows in set (0.01 sec)
mysql> select * from orchestra_instruments;
+-------+---------+
| oi_id | oi_name |
+-------+---------+
| 1 | Violin |
| 2 | Viola |
| 3 | Harp |
| 4 | Piccolo |
+-------+---------+
4 rows in set (0.00 sec)
mysql> select * from event_orchestra_musicians;
+-------------+---------------+----------+
| musician_id | instrument_id | event_id |
+-------------+---------------+----------+
| 1 | 1 | 2 |
| 2 | 1 | 2 |
| 3 | 3 | 2 |
| 4 | 2 | 2 |
+-------------+---------------+----------+
4 rows in set (0.00 sec)
select oi.oi_id, oi.oi_name, eom.musician_id
from orchestra_instruments oi
left join event_orchestra_musicians eom on oi.oi_id = eom.instrument_id
where (eom.event_id = 2 or eom.event_id is null)
order by oi.oi_id;
+-------+---------+-------------+
| oi_id | oi_name | musician_id |
+-------+---------+-------------+
| 1 | Violin | 1 |
| 1 | Violin | 2 |
| 2 | Viola | 4 |
| 3 | Harp | 3 |
| 4 | Piccolo | NULL |
+-------+---------+-------------+
5 rows in set (0.00 sec)