简体   繁体   中英

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

I have an issue when trying to fetch out my data from my database.

here are my table design

I have an issue when trying to fetch out my data from my database.

here are my table design

table1:

user_id    username
1          test
2          test2
3          test3

table2:

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

What i want to output is:

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

This is my current sql code:

 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"

However, this return nothing. Please help me in this.

Thanks.

Try following Query it will work for your problem:

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

Try using single quotes:

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'

Otherwise your query seems fine to me.

I've read this on SO in a comment: [S]ingle for [S]trings; [D]ouble for [D]atabase [S]ingle for [S]trings; [D]ouble for [D]atabase

Move your condition from where clause to on clause

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM