如何从子查询中访问列

问题描述 投票:0回答:3
  select u.phone, u.email , t.to_address (error from this)
  from user_accounts u 
  where u.id 
  in 
   (select w.user_id 
   from wallets w 
   where w.id 
   in 
     (
     select t.wallet_id 
     from withdraws t 
     where t.to_address 
     in 
     ('1F6o1fZZ7', 'pJDtRRnyhDN')))

我想从子查询中获取列to_address。我如何在postgresql中获取它?

我尝试为子查询指定'AS',但它不起作用

sql postgresql join
3个回答
1
投票

连接返回根据多个表的数据构造的结果表。您还可以使用子查询检索相同的结果表。子查询只是另一个select语句中的SELECT语句。

select u.phone, u.email , t.to_address (
 from user_accounts u 
INNER JOIN wallets w  ON u.id= w.user_id 
INNER JOIN withdraws t ON t.wallet_id =w.id 
  where t.to_address  in ('1F6o1fZZ7', 'pJDtRRnyhDN')

0
投票

使用连接所有表,你不需要任何子查询

 select u.phone, u.email , ww.to_address 
 from user_accounts u  left join wallets w  on u.id=w.user_id
  left jon withdraws ww on w.id=ww.wallet_id
where ww.to_address in ('1F6o1fZZ7', 'pJDtRRnyhDN')

您无法访问t.address,因为该列在in条件下。我使用left连接,但似乎它将是inner join类型,因为你使用过滤器in ('1F6o1fZZ7', 'pJDtRRnyhDN')虽然应用于条件后它也表现得像内连接


0
投票

您无法使用子查询实现正在尝试的内容。当您需要来自不同表的记录并且它们具有连接它们的唯一共同列时,您应该使用JOIN来执行此操作。

有时(并非所有情况)IN都会导致性能问题,所以你应该考虑更多地了解不同类型的JOINShttps://www.w3schools.com/sql/sql_join.asp

检查链接以进行比较:Inner join versus doing a where in clause

关于查询:

SELECT
  u.phone, u.email , t.to_address (error from this)
FROM
  user_accounts u 
  INNER JOIN wallets w ON u.id = w.id
  INNER JOIN withdraws t ON t.wallet_id = w.id
WHERE
  t.to_address IN ('1F6o1fZZ7', 'pJDtRRnyhDN')
© www.soinside.com 2019 - 2024. All rights reserved.