あなたは完全な外部結合を探しています。そうすれば、可能であれば両方のテーブルからすべてのレコードを取得します。残念ながら、MySQLは完全な外部結合をサポートしていないため、ここでは結合と左外部結合を使用するソリューションがあります。
私は3つのテーブル、companies
、contacts
、およびcompanies_contacts
を持っています。この最後のテーブルは関連テーブルです。ここでは3のそれぞれの内容は次のとおりです。
mysql> select * from companies;
+------------+---------+
| company_id | company |
+------------+---------+
| 1 | Foo |
| 2 | Bar |
| 3 | Baz |
+------------+---------+
3 rows in set (0.00 sec)
mysql> select * from contacts;
+------------+---------+
| contact_id | contact |
+------------+---------+
| 1 | Fred |
| 2 | Barney |
| 3 | Wilma |
| 4 | Betty |
+------------+---------+
4 rows in set (0.00 sec)
mysql> select * from companies_contacts;
+------------+------------+
| company_id | contact_id |
+------------+------------+
| 1 | 1 |
| 1 | 2 |
| 2 | 2 |
| 2 | 4 |
+------------+------------+
4 rows in set (0.00 sec)
あなたは少しそれを再考すると、問題が簡単になる:可能であれば自分に関連した企業と一緒に、あなたは基準を満たすすべての連絡先をしたい、とあなたはすべてしたいです可能であれば、関連する連絡先とともに、基準を満たす企業。
select company, contact
from companies
left join companies_contacts using (company_id)
left join contacts using (contact_id)
where company like '%B%';
そして:
select company, contact
from companies
right join companies_contacts using (company_id)
right join contacts using (contact_id)
where contact like '%W%';
を自分の結果を結合し、両者の間の任意の重複を排除するこれらの2つのクエリの間で労働組合を使用:
select company, contact
from companies
left join companies_contacts using (company_id)
left join contacts using (contact_id)
where company like '%B%'
union
select company, contact
from companies
right join companies_contacts using (company_id)
right join contacts using (contact_id)
where contact like '%W%';
を我々は2つの外部結合を使用して、これらの2つの問題を解決することができます
上記のデータでは、結果は次のようになります。
+---------+---------+
| company | contact |
+---------+---------+
| Bar | Barney |
| Bar | Betty |
| Baz | NULL |
| NULL | Wilma |
+---------+---------+
これはまさにあなたが探している結果です。
ありがとう、構文は何ですか? – sdfor
「LEFT OUTER JOIN」というより「FULL OUTER JOIN」と言っています。 –
ありがとう、私は実際に関連テーブルを通過しているので、両方の結合を完全にして問題を変更しないため、私の質問を編集しました – sdfor