SQL:DELETE,SELECT和LEFT JOIN-我可以这样做吗?

时间:2019-06-17 20:30:30

标签: sql postgresql

基本上,我试图取消关注喜欢的餐厅,并同时使所有关注的餐厅都没有被删除的餐厅,并且还从餐厅表中选择一个查询中的标题。

到目前为止,我已经知道了:

WITH deleted AS (DELETE from users_liked_restaurants WHERE users_liked_restaurants.user_id = 1 AND users_liked_restaurants.restaurant_id = 2 returning user_id)
SELECT restaurants.restaurant_id, restaurants.title FROM restaurants
LEFT JOIN users_liked_restaurants ON users_liked_restaurants.restaurant_id = restaurants.restaurant_id WHERE users_liked_restaurants.user_id = 1;

但是,这会通过user_id = 1返回所有喜欢的餐厅,包括我刚刚删除的餐厅。

2 个答案:

答案 0 :(得分:2)

原因是查询的两个部分都在同一条语句中运行,所以一个看不到另一个的影响。

让CTE返回已删除餐厅的restaurant_id,并从查询结果中排除这些餐厅:

WITH deleted AS (
  DELETE from users_liked_restaurants
  WHERE users_liked_restaurants.user_id = 1
    AND users_liked_restaurants.restaurant_id = 2
  RETURNING restaurant_id
)
SELECT restaurants.restaurant_id,
       restaurants.title
FROM restaurants
   LEFT JOIN users_liked_restaurants
      ON users_liked_restaurants.restaurant_id = restaurants.restaurant_id
WHERE users_liked_restaurants.user_id = 1
  AND NOT EXISTS (
         SELECT 1 FROM deleted
         WHERE deleted.restaurent_id = restaurants.restaurant_id
      );

答案 1 :(得分:2)

感谢您为Laurenz提供解决方案!工作完美。我也提出了类似的解决方案:

WITH deleted AS (
DELETE from users_liked_restaurants WHERE users_liked_restaurants.user_id = 1 
AND users_liked_restaurants.restaurant_id = 2 returning restaurant_id)
SELECT restaurants.restaurant_id, restaurants.title 
FROM restaurants
LEFT JOIN users_liked_restaurants ON users_liked_restaurants.restaurant_id = restaurants.restaurant_id WHERE users_liked_restaurants.user_id = 1 
AND users_liked_restaurants.restaurant_id != 2;

尽管我要使用Laurenz解决方案!再次感谢!