I have to insert a new row in table1 for each row found in table2. The problem is that the select in table2 returns more fields than are needed to the insert, but are useful in where clause of select.
This query shows to a user all the shops around, based on their (shops) range (defined in the table stores)
SELECT destination.poi_id,
6371 *
2 *
ASIN(
SQRT(
POWER(SIN((use_lat - poi_lat) * PI()/180 / 2), 2) +
COS(use_lat * pi()/180) *
COS(poi_lat * pi()/180) *
POWER(SIN((use_lon - poi_lon) * PI()/180 / 2), 2)
)
) AS distance,
destination.poi_range AS range
FROM stores destination, users origin
WHERE origin.use_id=userid
AND destination.poi_lon BETWEEN lon1 AND lon2
AND destination.poi_lat BETWEEN lat1 AND lat2
HAVING distance <= range
ORDER BY distance;
Now I have to put these results in a table having this structure
user_id INTEGER
poi_id INTEGER
ins_date TIMESTAMP (CURRENT TIMESTAMP)
I don't know how to do it, can you help me?
INSERT INTO table (user_id, poi_id)
SELECT ... ? (too many fields in select)
Reading between the lines a bit but basically only include the columns you need in the insert IE:
INSERT INTO table (user_id, poi_id)
SELECT use_id,poi_id,NOW() FROM
(SELECT origin.use_id,destination.poi_id,6371 *
2 *
ASIN(
SQRT(
POWER(SIN((use_lat - poi_lat) * PI()/180 / 2), 2) +
COS(use_lat * pi()/180) *
COS(poi_lat * pi()/180) *
POWER(SIN((use_lon - poi_lon) * PI()/180 / 2), 2)
)
) as distance
FROM stores destination, users origin
WHERE origin.use_id=userid
AND destination.poi_lon BETWEEN lon1 AND lon2
AND destination.poi_lat BETWEEN lat1 AND lat2
HAVING distance <= range) sub1
ORDER BY distance;