查询MySql中的多对多关系

时间:2017-01-26 13:14:47

标签: mysql sql many-to-many

假设我们有这个表a_b,这是与表a和b的多对多关系:

+------+------+
| a_id | b_id |
+------+------+
|    1 |    1 |
|    1 |    2 |
|    1 |    3 |
|    2 |    1 |
|    2 |    2 |
+------+------+

现在我想查询这个表,以便我得到所有a_ids,它们有一个b_id(1,2,3)的条目。在上面的例子中,输出应该是

+------+
| a_id |
+------+
|    1 |
+------+

原因a_id = 2没有b_id = 3

的条目

一个可能的查询是:

select *
from a
join a_b as a_b1 
    on a_b1.a_id = a.id and a_b1.b_id = 1
join a_b as a_b2 
    on a_b2.a_id = a.id and a_b2.b_id = 2
join a_b as a_b3 
    on a_b3.a_id = a.id and a_b3.b_id = 3

但是...... naaaa ...
对于这个问题,什么是更好的解决方案?

1 个答案:

答案 0 :(得分:2)

我认为更简单的方法是ObservableCollection<a_autor>System.Collections.ObjectModel.ObservableCollection<a_autor> _sourceCollection; private void UserControl_Loaded(object sender, RoutedEventArgs e) { var erg = db.a_autor; erg.Load(); _sourceCollection = new System.Collections.ObjectModel.ObservableCollection<a_autor>((from m in db.a_autor orderby m.at_id select m).ToList()); box.ItemsSource = _sourceCollection; } private void loeschen_Click(object sender, RoutedEventArgs e) { a_autor am = (a_autor)box.SelectedItem; if (am != null) { _sourceCollection.Remove(am); db.a_autor.Remove(am); db.SaveChanges(); box.Items.Refresh(); } } private void neu_Click(object sender, RoutedEventArgs e) { a_autor autor = new a_autor(); autor.at_id = id.Text; autor.at_vorname = vorname.Text; autor.at_nachname = nachname.Text; autor.at_gebDatum = Convert.ToDateTime(datum.Text); _sourceCollection.Add(autor); db.a_autor.Add(autor); box.Items.Refresh(); }

group by