27

My question is related to the answer found in this post by user Consultuning on Oct 22 '09 at 18:31: mysql query to dynamically convert row data to columns

It appears that Consultuning's answer contains some MySQL with a For Each row loop.

Can you do a For Each Row loop using MySQL?

If so, could someone give me a link to the MySQL For Each Row documentation?

Community
  • 1
  • 1
zechdc
  • 3,374
  • 9
  • 40
  • 52

3 Answers3

19

The closest thing to "for each" is probably MySQL Procedure using Cursor and LOOP.

panupan
  • 1,212
  • 13
  • 15
5

Not a for each exactly, but you can do nested SQL

SELECT 
    distinct a.ID, 
    a.col2, 
    (SELECT 
        SUM(b.size) 
    FROM 
        tableb b 
    WHERE 
        b.id = a.col3)
FROM
    tablea a
Jeric Cruz
  • 1,899
  • 1
  • 14
  • 29
Kudapucat
  • 51
  • 1
  • 1
2

In the link you provided, thats not a loop in sql...

thats a loop in programming language

they are first getting list of all distinct districts, and then for each district executing query again.

Zohaib
  • 7,026
  • 3
  • 26
  • 35
  • 1
    I guess my question should be, Can you do a `for each row` loop using mysql? – zechdc Nov 03 '11 at 04:37
  • as far as i know, u can't do that via pure SQL. The link u r referring to in ur comment is basically explanation of the nested query join algorithm. it simple explains how MYSQL fetches data when there is a join involved on two columns. @zechdc – Zohaib Nov 03 '11 at 04:38
  • 1
    Ok, that makes sense. So really I need to be using a `join` to get something similar to a `for each` – zechdc Nov 03 '11 at 04:45