Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL foreach loop

Tags:

sql

I'm very new at SQL scripts and couldn't figure out how to make a specific for each loop. I need to do something like this:

I have Sites and SiteCrawls tables.

Basically, for every site I need to create a new SiteCrawl and that SiteCrawl's Site_ID column will equal to that site's ID.

How can I do this?

like image 307
heaten Avatar asked Nov 28 '11 16:11

heaten


4 Answers

insert SiteCrawl
(
    Site_ID
)
select
 s.Site_ID
from Site as s
where s.Site_ID not in (select Site_ID from SiteCrawl)
like image 112
canon Avatar answered Oct 27 '22 21:10

canon


insert into site_crawl (site_id) values (select site_id from site);

So basically: there is no specific for/each in plain SQL, you handle tables and rows of results always as one statement. So you could also say: there is no way an SQL Statement is something else than a for/each. With that knowledge, you can see that the above query will insert one row into site_crawl for every site_id in the site table. You most likely want to use more values than this, but given the information from your question that is all I can do for you :)

Also: you want to read more about what sql is and how its used.

Have fun, SQL is a lot of fun!

like image 42
Angelo Fuchs Avatar answered Oct 27 '22 23:10

Angelo Fuchs


In SQL you typically don't want to loop over every record. It's very inefficient.

You could do something like

insert into SiteCrawl (Site_Id)
select Id from Sites
like image 3
taylonr Avatar answered Oct 27 '22 22:10

taylonr


insert into SiteCrawls (SiteID)
select SiteID 
  from Sites
like image 1
datagod Avatar answered Oct 27 '22 21:10

datagod