Loop with SQL queries... I'm a newbie!

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
obrienmd
Forum Newbie
Posts: 2
Joined: Fri Nov 13, 2009 6:47 pm

Loop with SQL queries... I'm a newbie!

Post by obrienmd »

I haven't touched code since BASIC in about 1995 (please don't hold it against me) :)

I would like to code a loop which does the following:

For (# of times VariableA shows up in TableX)
SELECT ColumnM from TableX (nth occurance, N being stepped through in the loop), store as VariableB
SELECT ColumnN FROM TableY WHERE ColumnO = VariableB, store as VariableC
add VariableC to VariableD (running total)
Loop

Does this make any sense?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Loop with SQL queries... I'm a newbie!

Post by requinix »

If I'm reading that right you can do it all in one query. Just one.

Code: Select all

SELECT SUM(TableY.ColumnN) FROM TableY JOIN TableX ON TableX.ColumnM = TableY.ColumnO WHERE (some condition involving TableX)
obrienmd
Forum Newbie
Posts: 2
Joined: Fri Nov 13, 2009 6:47 pm

Re: Loop with SQL queries... I'm a newbie!

Post by obrienmd »

Thanks! Everything is making complete sense up to the "some condition involving tableX"... Any further explanation you can do on that?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Loop with SQL queries... I'm a newbie!

Post by requinix »

obrienmd wrote:Thanks! Everything is making complete sense up to the "some condition involving tableX"... Any further explanation you can do on that?
You didn't quite say how you figured "# of times VariableA shows up in TableX".

The condition is just whatever you use to total that number. Like if you want "# of times ColumnP is the value 'foo'" then the condition would be

Code: Select all

WHERE TableX.ColumnP = "foo"
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Loop with SQL queries... I'm a newbie!

Post by John Cartwright »

For us to answer that, you will have to describe "# of times VariableA shows up in TableX" in more detail. Can VariableA exist within multiple columns, and is VariableA the only value in the columns? I.e. do you need to search for VariableA within the column value, or is it the column value?
Post Reply