-2

I am trying to get the row data from the database table to a label the condition is I want the highest value column to be displayed in the label with other fields currently my code is :

 private void electionWinner()
        {
           
            try
            {
                conn.Open();
                string qry = "SELECT * FROM Results WHERE (SELECT MAX(Results) FROM Results) ";
                SqlCommand cmd = new SqlCommand(qry,conn);
                string result = cmd.ExecuteReader().ToString();
                winnerlbl.Text = result.ToString();

            }
            catch (SqlException es)
            {

                MessageBox.Show($"{es}");
            }

        }
    }

I am currently new to c# and trying to understand it, so I am lost, thanks in advance.

Useme Alehosaini
  • 2,998
  • 6
  • 18
  • 26
Anjelo
  • 13
  • 1
  • 4
  • You forgot to add that you are new to SQL tooo. What database are you using? (please add the correct [tag] for that.) – Luuk Mar 28 '21 at 10:40
  • Database used is mysql –  Anjelo Mar 28 '21 at 10:43
  • check this before https://stackoverflow.com/questions/15946089/find-max-value-and-show-corresponding-value-from-different-field-in-sql-server it will help you with SQl Max – Lajil Adel Mar 28 '21 at 10:44
  • I doubt you are using together a MySql database and the classes for Sql Server . – Steve Mar 28 '21 at 10:45
  • If your database is mysql then you are using the wrong provider. SqlCommand, etc, is for microsoft sql server. Also look up how to use readers, you cannot simply ToString the result – Crowcoder Mar 28 '21 at 10:48

3 Answers3

1

The query itself isn't correct. here's why:

  1. you did not state which column in the Results table that you want the max of

  2. When you adjust the select statement inside the where clause, you need to make sure your WHERE statement will either give you a true or false, currently all it does is get the max value (if you correctly add the column name)

    select * from Results where COLUMNNAME= (select Max(COLUMNNAME) from Results)

Always make sure to run the query on the database before doing it inside your code

Boruj
  • 34
  • 6
1

Use ORDER BY and LIMIT:

SELECT r.*
FROM Results r
ORDER BY r.Results DESC
LIMIT 1;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
-1

You can modify your query like below

             `string qry = "Select ColumnName From Results where  ColumnName in (SELECT Max(ColumnName) FROM Results)";`