SQL JOIN从两个表中获取详细信息

时间:2012-12-15 06:56:46

标签: sql sql-server database

我有3张桌子

  1. User_Details包含列(user_id, name
  2. Stock_Details包含列(user_id foreign key, stocks
  3. Billing_Details包含列(user_id foreign key, billing
  4. 如何使用Stock_Detailsbilling_Details

    显示用户列表

3 个答案:

答案 0 :(得分:2)

SELECT u.user_id,
       u.name,
       b.billing,
       s.stocks
FROM user_details u
LEFT JOIN billing_details b on b.user_id = u.user_id
LEFT JOIN stock_details s on s.user_id = u.user_id

答案 1 :(得分:1)

请尝试:

SELECT 
    T1.user_id,
    T1.name,
    T2.stocks,
    T3.billing
FROM
    User_Details T1 INNER JOIN Stock_Details T2 ON T1.User_id=T2.User_id
        INNER JOIN Billing_Details T3 ON T2.User_id=T3.User_id

答案 2 :(得分:0)

如果您想显示库存表或结算表中的记录,请尝试此操作...

select <your required fields> 
From User_Details ud inner join Stock_Details sd on ud.user_id=sd.user_id
Union 
select <your required fields> 
From User_Details ud inner join billing_Details bd on ud.user_id=bd.user_id
where ud.user_id not in (select user_id from stock_details)

注意:联合和相同顺序的字段相同。否则返回错误..