如何从mysql中的2个不同表中获取数据

时间:2013-05-03 05:00:12

标签: mysql

我有两张桌子:

Subscriber_detail

SubscriberID | Merchant_ID 
23           |  24

User_Detail

User_ID | User_RegisteredID

23      | 1001001
24      | 1001002

需要从User_RegisteredID

User_Login表中提取SubscriberID and Merchant_ID from Subscriber_Detail

1 个答案:

答案 0 :(得分:1)

SELECT  sub.User_RegisteredID AS SubscriberRegisteredID,
        mer.User_RegisteredID AS MerchantRegisteredID
FROM    Subscriber_detail s
        JOIN User_Detail sub on s.SubscriberID = sub.User_ID
        JOIN User_Detail mer ON s.Merchant_ID = mer.User_ID

您需要加入两个表,并且User_Detail应该连接两次,因为表Subscriber_detail中有两列被引用。

如果一列 NULLABLE ,则应使用LEFT JOIN

SELECT  sub.User_RegisteredID AS SubscriberRegisteredID,
        mer.User_RegisteredID AS MerchantRegisteredID
FROM    Subscriber_detail s
        LEFT JOIN User_Detail sub on s.SubscriberID = sub.User_ID
        LEFT JOIN User_Detail mer ON s.Merchant_ID = mer.User_ID