简体   繁体   中英

How to show two rows with same id in two different columns in datagridview using mysql?

I have two tables here.

1st for user with user_id and name and 2nd for contacts with contact_id,contact(2 against 1 user_id) and user_id(foreign key)

Can i split the contacts in two columns of datagridview? like

User ID=1   Name=Ausaf   Contact1=0300468945    Contact2=0300733455

If it is possible, how should I do it? I am using the following code to retrieve the values from database

string sql = "select user.user_id as 'User ID', name as 'Name',contact as 

'Contact' from biometric_attendance_system.user JOIN 

    biometric_attendance_system.contact ON user.user_id=contact.user_id";

 try
 {
     MySqlDataAdapter load = new MySqlDataAdapter();
     load.SelectCommand = sql1;

     DataTable dt = new DataTable();
     load.Fill(dt);

     BindingSource bs = new BindingSource();
     bs.DataSource = dt;

     dataGridView1.DataSource = bs;
     load.Update(dt);
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

you may use something like this, keeping in mind that there are no, only one or a maximum of two contacts only

SELECT u.user_id AS 'User ID', u.user_name AS 'Name', c1.contact_num AS 'Contact1', c2.contact_num AS 'Contact2'
FROM
    users u
    LEFT OUTER JOIN (SELECT a.user_id, a.contact_id, b.contact_num FROM (SELECT user_id, MIN(contact_id) AS contact_id FROM contacts GROUP BY 1) a INNER JOIN contacts b ON a.contact_id=b.contact_id) c1 ON c1.user_id=u.user_id
    LEFT OUTER JOIN (SELECT a.user_id, a.contact_id, b.contact_num FROM (SELECT user_id, MAX(contact_id) AS contact_id FROM contacts GROUP BY 1) a INNER JOIN contacts b ON a.contact_id=b.contact_id) c2 ON c2.user_id=u.user_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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