将数据从另一个表插入表中,并消除某些列中的重复项

时间:2017-05-07 18:42:03

标签: sql sqlite

我有一张名为HotelReviews的桌子,我希望用HotelReviews的数据填充另一张名为Hotels的桌子。

这些是HotelReviews所拥有的一些列:hotel_id,价格,评级,网址,作者,内容......所以输入的示例可能是:

INSERT INTO HotelReviews(hotel_id, price, rating, url, author, content...) VALUES (65729, 100, 4, ''http://www.tripadvisor.com/...', 'rick76', 'I enjoyed my stay.'...);

INSERT INTO HotelReviews(hotel_id, price, rating, url, author, content...) VALUES (65729, 100, 4, ''http://www.tripadvisor.com/...', 'eve66', 'I enjoyed my stay.'...);

这表明两位用户已为同一家酒店撰写评论。

酒店有以下栏目:hotel_id,价格,评级,网址

hotel_id和url是独一无二的,因此我需要删除重复项并仅为每家酒店提供一次信息。

我试图这样做,但它不起作用:

INSERT INTO Hotels(hotel_id, price, rating, url)
SELECT DISTINCT hotel_id, price, rating, url
FROM HotelReviews;

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

假设您在这两列上定义了唯一约束,则可以使用INSERT OR IGNORE

insert or ignore into hotels(hotel_id, price, rating, url)
select hotel_id,
    price,
    rating,
    url
from hotelreviews;

答案 1 :(得分:1)

怎么样?
INSERT INTO Hotels(hotel_id, price, rating, url)
SELECT hotel_id, price, rating, url 
FROM (
  SELECT DISTINCT hotel_id, price, rating, url
  FROM HotelReviews
)