【问题标题】:Select corresponding rows from another table for each row in first table in mysql为mysql中第一个表中的每一行从另一个表中选择对应的行
【发布时间】:2019-03-04 13:17:44
【问题描述】:

我有一个名为 users 的表,另一个名为 withdraws 的表,

如何为来自用户的每个提款请求选择一行,并在用户表中使用他的银行详细信息。

重要提示:用户表中的 user_name 对于每一行都是唯一的。这对应于withdraws表中的userid

这里是, 用户表

+-----------+-----------------+-------------+
| user_name | bank_ac         | ifsc        |
+-----------+-----------------+-------------+
| H6426012  | 456456 | ifsc6544 |
+-----------+-----------------+-------------+

撤销表

+----------+--------+--------+
| userid   | amount | status |
+----------+--------+--------+
| H6426012 | 300.00 |      1 |
| H6426012 | 150.00 |      1 |
| H6426012 | 200.00 |      1 |
+----------+--------+--------+

这是我正在使用的查询:

select withdraws.userid 
     , withdraws.amount
     , users.user_name
     , users.ifsc
     , users.bank_ac 
  from withdraws 
  JOIN users 
    on withdraws.userid = users.user_name 
 where withdraws.status = 1

这是我期待的结果:

我期待这个结果

+----------+--------+--------++----------+--------+--------+
| userid   | amount | status |user_name   | ifsc | bank_ac |
+----------+--------+--------++----------+--------+--------+
| H6426012 | 300.00 |      1 | H6426012 | ifsc6544 | 456456 |
| H6426012 | 150.00 |      1 | H6426012 | ifsc6544 | 456456|
| H6426012 | 200.00 |      1 | H6426012 | ifsc6544 | 456456 |
+----------+--------+--------++----------+--------+--------+

但我得到了这个结果

+----------+--------+--------++----------+--------+--------+
| userid   | amount | status |user_name   | ifsc | bank_ac |
+----------+--------+--------++----------+--------+--------+
| H6426012 | 300.00 |      1 | NULL      | NULL    | NULL |
| H6426012 | 150.00 |      1 | NULL      | NULL    | NULL|
| H6426012 | 200.00 |      1 | NULL      | NULL    | NULL |
+----------+--------+--------++----------+--------+--------+

【问题讨论】:

  • 您使用的查询完全不可能。如果您使用LEFT JOIN,那么我会说“检查不可见字符”之类的。但是根据您当前的查询,您要么得到想要的结果,要么根本没有结果。
  • 我也使用了 LEFT JOIN,但仍然得到相同的结果。
  • NULL 值对于您当前的查询是不可能的 RameshPareek @fancyPants 是正确的,请参阅 db-fiddle.com/f/vWEFa4Ka6xLG7cg8HoaJ3q/0
  • 对红旗的家伙们感到抱歉。原因是数据库更新为 NULL 值。所以你的 cmets 真的帮助我重新查看了数据库实际上有哪些值,发现它是 NULL。

标签: mysql


【解决方案1】:

我运行了相同的查询,它运行良好,我还创建了相同的查询,但没有任何连接,它运行良好...... 我正在使用 SQL Server Management Studio V17.9。

【讨论】:

  • 接受您的回答:)。感谢您的努力。我已经意识到数据库中的值实际上是 NULL。
【解决方案2】:

首先在您的 users 架构/表上将 user_name 更改为 user_id,以免将来混淆您。然后,像下面这样修改您的查询,然后它就可以正常工作了

select users.userid as user_id, 
     withdraws.amount as amount,
     withdraws.status as status
     users.ifsc as ifsc
     users.bank_ac as bank_ac
  from withdraws 
  JOIN users 
    on withdraws.userid = users.userid 
 where withdraws.status = 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    相关资源
    最近更新 更多