ZKE ZKE - 6 months ago 13
SQL Question

MySQL insert into a table from multiple table filter by id

i'm try to insert into a table from multiple table.

here's my table

provinces table :
id , name

regencies table :
id , province_id , name

districts table :
id , regency_id , name

villages table :
id , district_id , name


i want to insert into a table with this structure :

tb_all
id , id_villages , villages_name ,
id_districts , districts_name ,
id_regency , regency_name ,
id_provinces , provinces_name


i'm really newbie about mysql command.

here's my query :

INSERT INTO tb_all (
id_villages,
villages_name,
id_districts,
districts_name,
id_regency,
regency_name,
id_provinces,
provinces_name)

SELECT v.id,
v.name,
d.id,
d.name,
r.id,
r.name,
p.id,
p.name

FROM villages AS v,
districts AS d,
regencies AS r,
provinces AS p

WHERE p.id = '73'


but i got this error :

**Error : Lock wait timeout exceeded**


i appreciate for any answer. thx.

Edit 2 :
another problem is when i run this query, my disk almost full :(

Answer

You should join your tables linking foreign keys to primary keys, otherwise you are generating a Cartesian product, which will not be what you want, and may run your database engine to its limits.

As you wrote in comments, you do filter the villages records to 18,000 records. But you don't filter at all the other tables, of which regencies may have more than 5,000 records, districts 200, and provinces maybe 50. So you'd get the multiplication as the result set: 18,000 x 5,000 x 200 x 50 = 900 billion records!

Here is a suggested query. I suggest you first run the part that starts with SELECT to see if produces the correct records. Then when that is OK, run the INSERT:

INSERT INTO tb_all (
            id_villages,
            villages_name,
            id_districts,
            districts_name,
            id_regency,
            regency_name,
            id_provinces,
            provinces_name)
SELECT      v.id,
            v.name,
            d.id,
            d.name,
            r.id,
            r.name,
            p.id,
            p.name
FROM        provinces AS p
INNER JOIN  regencies AS r
        ON  r.province_id = p.id
INNER JOIN  districts AS d
        ON  d.regency_id = r.id
INNER JOIN  villages AS v
        ON  v.district_id = d.id
WHERE       p.id = 73
Comments