简体   繁体   English

具有多个表联接查询的C#datagridview

[英]C# datagridview with multiple table join query

I have a question on how to bind data to a datagridview in C# when using a JOIN query with a mySql datasource, and I return one unique record from the first table and 0-2 records from a second table. 我有一个问题,如何在将结合查询与mySql数据源一起使用时,如何将数据绑定到C#中的datagridview上,我从第一个表返回一个唯一记录,而从第二个表返回0-2个记录。 My query is as follows: 我的查询如下:

SELECT t1.*, t2.org_id, t2.org_name 
FROM test.tbl_user_accounts AS t1 
INNER JOIN test.tbl_organizations AS t2 
ON t1.affiliation_one = t2.org_id OR t1.affiliation_two = t2.org_id;

It's a school assocation, where a user can be associated with up to two schools. 这是一个学校关联,其中一个用户最多可以与两个学校关联。 I want the schools to display in separate cells so a GROUP_CONCAT isn't really a good option, and if I use GROUP BY on the t1.user_id field then I lose the second affiliation. 我希望学校显示在单独的单元格中,因此GROUP_CONCAT并不是一个很好的选择,如果我在t1.user_id字段上使用GROUP BY,那么我将失去第二个从属关系。 If I don't group, I end up with two rows for the same user. 如果不分组,则同一用户将得到两行。

I'm not all that familiar with joins, so it's possible that a different type of join might solve this? 我对联接不是很熟悉,因此有可能使用其他类型的联接来解决此问题?

I'm using Visual C# 2010, with a mySql datasource. 我正在使用带有MySql数据源的Visual C#2010。

Here's the query I used to solve this (I think I found it in another stack post, actually). 这是我用来解决此问题的查询(实际上,我认为是在另一个堆栈文章中找到的)。

SELECT test.tbl_user_accounts.*, t2.org_name as affil_one, t3.org_name as affil_two,t4.rank_name as rank_name
FROM test.tbl_user_accounts 
LEFT JOIN (test.tbl_organizations as t2) ON (t2.org_id = test.tbl_user_accounts.affiliation_one)
LEFT JOIN (test.tbl_organizations as t3) ON (t3.org_id = test.tbl_user_accounts.affiliation_two)
LEFT JOIN (test.tbl_ranks as t4) ON (t4.id_rank = test.tbl_user_accounts.user_rank);

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

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