簡體   English   中英

MySQL SELECT全部來自第一個表,並使用第二個表過濾器的特定where子句連接來自第二個表的匹配數據

[英]MySQL SELECT all from first table and join matched data from second table with specific where clause for second table filter

嘗試從數據庫中獲取數據時出現問題。

這是我的桌子設計

嘗試從數據庫中獲取數據時出現問題。

這是我的桌子設計

表格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"

但是,這什么也沒有返回。 請幫助我。

謝謝。

嘗試執行以下查詢,它可以解決您的問題:

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

嘗試使用單引號:

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 [S]ingle for [S]trings; [D]ouble for [D]atabase

將條件從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"

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM