【问题标题】:MySQL SELECT all from first table and join matched data from second table with specific where clause for second table filterMySQL 从第一个表中选择全部,并使用第二个表过滤器的特定 where 子句连接第二个表中的匹配数据
【发布时间】:2014-09-09 09:53:15
【问题描述】:

我在尝试从数据库中提取数据时遇到问题。

这是我的餐桌设计

我在尝试从数据库中提取数据时遇到问题。

这是我的餐桌设计

表1:

user_id    username
1          test
2          test2
3          test3

表2:

id         table2_userid   key        value
1          2               position   admin
2          2               name       myname

我要输出的是:

user_id     username       key        value
1           test           NULL       NULL
2           test2          position   admin
3           test3          NULL       NULL

这是我当前的sql代码:

 SELECT table1.user_id, table1.username, table2.key, table2.value 
 FROM table1 
 LEFT JOIN table2 ON table1.user_id = table2.table2_userid WHERE table2.key="position"

但是,这不会返回任何内容。请帮帮我。

谢谢。

【问题讨论】:

  • 您的问题出在 WHERE 子句上。强制 key='position' 消除空结果。尝试 WHERE table2.key="position" 或 table2.key 为 NULL
  • 这种方式也行不通。 Robin Saxena 和 M Khalid Junaid 解决问题的解决方案。谢谢顺便说一句

标签: mysql sql select join where


【解决方案1】:

尝试以下查询,它将解决您的问题:

SELECT table1.user_id, table1.username, table2.key, table2.value FROM 
table1 LEFT JOIN table2 ON table1.user_id = table2.table2_userid and 
table2.key="position" group by table1.user_id

【讨论】:

    【解决方案2】:

    尝试使用单引号:

    SELECT table1.user_id, table1.username, table2.key, table2.value 
    FROM table1 
    LEFT JOIN table2 ON table1.user_id = table2.table2_userid WHERE table2.key = 'position'
    

    否则您的查询对我来说似乎很好。

    我在 SO 上的评论中读到了这篇文章:[S]ingle for [S]trings; [D]ouble for [D]atabase

    【讨论】:

      【解决方案3】:

      将条件从 where 子句移到 on 子句

      SELECT 
      t1.user_id, 
      t1.username, 
      t2.key, 
      t2.value 
      FROM table1 t1 
      LEFT JOIN table2 t2
      ON t1.user_id = t2.table2_userid 
      AND t2.key="position"
      

      Demo

      【讨论】:

      • 你的也可以。谢谢。但是我首先从 Robin Saxena 那里得到了答案,所以我不能选择你作为我的答案。抱歉,非常感谢:D
      猜你喜欢
      • 2013-05-30
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多