我必须在table1中为table2中的每一行插入一个新行。 问题是table2中的select返回的字段多于insert所需的字段,但在select的where子句中很有用。
此查询根据用户(商店)范围(在表商店中定义)向用户显示周围的所有商店
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;
现在我必须将这些结果放在具有这种结构的表中
user_id INTEGER
poi_id INTEGER
ins_date TIMESTAMP (CURRENT TIMESTAMP)
我不知道该怎么做,你能帮助我吗?
INSERT INTO table (user_id, poi_id)
SELECT ... ? (too many fields in select)
答案 0 :(得分:1)
在行之间读取一点但基本上只包括插入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;
答案 1 :(得分:0)
您只需添加select select_id并删除距离和范围,因为您的表中没有,实际上您必须添加ins_date,因为您没有在Insert中定义 VALUE 语句。所以你的选择应该是这样的
INSERT INTO table values (user_id, poi_id)
Select user_id, poi_id from 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;
如果您需要在表格中添加日期,请在括号内包含此字段,也可在