【问题标题】:use a mysql query result to do another query使用 mysql 查询结果进行另一个查询
【发布时间】:2015-01-28 07:38:19
【问题描述】:

我有 2 个表 table1 包含一个用户 ID 和一个 postid。表 2 包含一个用户 ID 和一个用户名。我想返回具有某个 postid 的所有用户 ID,然后使用这些用户 ID 查询 table2 并获取用户名。

有没有办法解决这个问题?我已经尝试过 join 语句,它似乎不起作用

【问题讨论】:

  • 添加您在问题中尝试过的查询

标签: mysql nested-queries


【解决方案1】:

使用 IN 函数:

select username, userid from `table2` where userid in (select userid from `table` where postid = <condition>)

【讨论】:

  • 现在如果我想从表中返回comment_id以及用户名和用户ID怎么办?
  • @JohnSmith 您能否将表格创建语句添加到您的问题中?
【解决方案2】:
SELECT A.postid, A.userid, B.username FROM
tableA AS A JOIN tableB AS B ON A.userid=B.userid

select post id, user id from tableA 用户名 from tableB。当 tableA 的 userid 等于 tableB 的 userid 时,加入这 2 个不同的表列。

【讨论】:

    【解决方案3】:
    select t1.postid, t1.userid, t2.username
    from table1 t2
    left join table1 t2 on t1.userid = t2.userid
    where t1.postid = <your postid>
    

    【讨论】:

      【解决方案4】:

      在公共列上加入表格

      select t1.postid, t1.userid, t2.username
      from table1 t1
      join table2 t2 on t1.userid = t2.userid
      where t1.postid = 2
      

      【讨论】:

      • 但它必须是我设置特定 postid 的地方。所以就像 if posted = 2 返回 userid 然后根据 userid 搜索 table2 得到用户名
      • 我在最后添加到查询中
      • 现在,如果我还想从 table1 返回一个 comment_id 怎么办。现在假设 table1 包含一个 comment_id 字段
      • 然后在选择部分添加。你真的应该学习 SQL 教程。这是非常基础的,没有基础知识你不会走得太远。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      相关资源
      最近更新 更多