【问题标题】:Insert into table1 from table2 based on conditions from table3根据表 3 中的条件从表 2 插入表 1
【发布时间】:2021-07-11 00:26:05
【问题描述】:

你好,我有一些问题:

我有 3 张桌子

用户

username tele notify
user1 555-123456 true
user2 555-000123 false
user3 null false

表格datesTimes

date userame
2021-10-10 user1
2021-10-10 user2
... ...

表格out_notifications

telephone message

现在我想将数据从表 datesTimes 插入表 out_notifications,仅适用于打开电话号码和通知的用户。

所以我构造了以下查询:

INSERT INTO out_notifications (telephone,message)
SELECT (select tele from users where users.username = datesTimes.username),
       'some message'    --(generated by system)
FROM datesTimes
WHERE date = '2021-10-10';

现在在哪里放置一个子查询,它只选择带有电话的用户。号码和通知是否开启?

使用数据库 PostgreSQL

感谢您的帮助。

【问题讨论】:

  • 听起来你想做一个简单的 INNER JOIN。在 postgres 中看起来像:'INNER JOIN users ON users.username = datetimes.username'。之后,您可以添加 WHERE users.notify = 'true'。希望这会有所帮助

标签: sql postgresql


【解决方案1】:

使用连接而不是子选择。

INSERT INTO out_notifications (telephone,message)
  SELECT users.tele,
     'some message'    --(generated by system)
  FROM users 
  JOIN datesTimes
      ON users.username = datesTimes.username,
  WHERE datesTimes.date = '2021-10-10'
    AND users.tele <> ''
    AND users.notify; 

【讨论】:

  • 我以为没有加入就行不通,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
  • 2020-10-01
  • 2020-06-09
  • 2015-09-27
  • 2014-01-05
  • 2021-11-03
相关资源
最近更新 更多