Skip to content
Advertisement

Subquery returns more than 1 rows

This is a beginner of coding trying to figure out how query works.

Right now I’m trying to select a specific column of several different rows from mysql and display them at the same row on C#, somehow I got error saying

Subquery returns more than 1 row

After hours of thinking, still can’t figure out the solution. Wish I could get help here.

Here’s my code below:

Select Distinct T, DAY, TIME 
from climate
Where DAY in (
  Select Distinct DAY
  where DAY = '2020-01-22'
    and DISTRICT in
    (
      Select Distinct DISTRICT
      Where DISTRICT = '" + cmbArea.Text + "'
        and CITY in
        (
          Select Distinct CITY
          Where CITY = '" + cmbCity.Text + "'
        )
    )
)

Advertisement

Answer

The query is weird. Let’s look at the innermost expression:

[WHERE] city IN (SELECT DISTINCT city WHERE city = '...')

In the subquery you are not selecting from any table, so you are merely refering to the city from its parent query. The WHERE clause looks at one row at a time. So there is one row with one city. You compare this city with some variable and if it is a match you select this city. If not, then not. Then you use DISTINCT on the one or zero values as if there could be duplicates to remove. And then you’re using IN which works with duplicates and without, so we would not force the DBMS to make rows distinct anyway. This complex expression is nothing else than

[WHERE] city = '...'

The whole query is

SELECT DISTINCT t, day, time 
FROM climate 
WHERE day = DATE '2020-01-22' 
AND district = @district
AND city = @city;

Even DISTINCT may be unnecessary here, but I can’t know for sure. It depends on the table’s unique key.

In C# you’d use something along the lines of:

MySqlCommand mySqlCommand = new MySqlCommand("SELECT ...", conn);
mySqlCommand.Parameters.Add(new MySqlParameter("@district", district));
mySqlCommand.Parameters.Add(new MySqlParameter("@city", city));
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(mySqlCommand);

I don’t see, though, how any of your pseudo subqueries could return more than just one value.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement