instead of
LEFT JOIN Table2
try:
LEFT JOIN (Select id, locationId from table2 group by id, locationId having count(*) = 1) as table2
質問
Working with the following:
string strSelectSql = "SELECT Table1.ID, Table1.Status,
Table1.CustomerName,Table1.Date, Table1.LocationID,
Table2.LocationID As [LocationID 2] FROM Table1 LEFT JOIN
Table2 ON Table1.ID = Table2.ID
WHERE (Date Is Null AND ID= @SearchForString AND
Status != 'Archived') OR
((Date Between @FromDate AND @ToDate)
AND ID= @SearchForString AND Status != 'Archived')";
SqlConnection SqlConn = new SqlConnection(cstrDatabaseConnection);
SqlDataAdapter SqlAdpt = new SqlDataAdapter();
SqlCommand SqlCom = new SqlCommand(strSelectSql,SqlConn);
SqlCom.Parameters.AddWithValue("@SearchForString",strSearchString);
SqlCom.Parameters.AddWithValue("@FromDate",strFromDate);
SqlCom.Parameters.AddWithValue("@ToDate",strToDate );
SqlAdpt.SelectCommand = SqlCom;
try
{
DataSet TempDS = new DataSet();
SqlConn.Open();
SqlAdpt.Fill(TempDS);
SqlConn.Close();
SqlConn.Dispose();
if (Convert.ToInt32(TempDS.Tables[0].Rows.Count) > 0)
{
dgvQueryResult.DataSource = TempDS.Tables[0];
dgvQueryResult.Refresh();
dgvQueryResult.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
TempDS.Dispose();
}
}
catch (SqlException sqlE)
{
MessageBox.Show(sqlE.Message);
SqlConn.Close();
SqlConn.Dispose();
}
catch (Exception UnknownE)
{
MessageBox.Show(string.Format("Unknown Exception: {0}",UnknownE.Message);
SqlConn.Close();
SqlConn.Dispose();
}
finally
{
if (SqlConn != null) SqlConn.Dispose();
}
Now this all works fine and dandy unless Table2 has Multiple values for LocationID
Table2
+----+------------+
| ID | LocationID |
+----+------------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
| 6 | 6 |
| 6 | 7 |
| 6 | 7 |
| 7 | 8 |
| 7 | 9 |
+----+------------+
I want to ignore the:
Table2
+----+------------+
| ID | LocationID |
+----+------------+
| 6 | 7 |
| 6 | 7 |
+----+------------+
and Get this:
Table2
+----+------------+
| ID | LocationID |
+----+------------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
| 6 | 6 |
| 7 | 8 |
| 7 | 9 |
+----+------------+
but I do want the:
Table2
+----+------------+
| ID | LocationID |
+----+------------+
| 6 | 6 |
+----+------------+
Because the LocationID is not duplicated.
Also, I DO want:
Table2
+----+------------+
| ID | LocationID |
+----+------------+
| 7 | 8 |
| 7 | 9 |
+----+------------+
again because the LocationID is not duplicated.
If I have to or if it will be more Efficient I also willing to remove these rows from the TempDS before:
dgvQueryResult.DataSource = TempDS.Tables[0];
If even if need be or if most efficient remove the entries right from dgvQueryResult
解決
instead of
LEFT JOIN Table2
try:
LEFT JOIN (Select id, locationId from table2 group by id, locationId having count(*) = 1) as table2