如何合并来自2个不同表的select语句,我需要表1中的by_user_id表2选择statment来获取用户名?

时间:2015-10-24 14:40:34

标签: sql sql-server sql-server-2008

如何合并来自2个不同表的select语句,我需要表1中的by_user_id表2选择statment来获取用户名?

SELECT ans, by_user_id, datetime 
FROM answer 
WHERE qn_id = :qn_id
UNION
SELECT username 
FROM user 
WHERE by_user_id = ???

1 个答案:

答案 0 :(得分:1)

我相信你的意思只是JOIN

SELECT a.ans, a.by_user_id, a.datetime ,
    u.username
FROM answer a
LEFT JOIN user u
ON a.by_user_id = u.id 
WHERE qn_id = :qn_id