MySQL自引用JOIN

时间:2019-03-19 17:56:15

标签: join self-reference mysql5

我有两个表:

Customers (
    int(11) Id, 
    varchar(255) Name, 
    int(11) Referred_ID -- Referred_ID being reference to an Id field 
                        -- (no key on that field) and 
)

另一个表是:

Invoices (
    int(11) Id, 
    date Billing_date, 
    int(11) Customer_ID
)

我要选择发票中的IdBilling_date,最重要的是,该客户指的是客户的Name

现在,我只能通过这样的查询来选择其推荐人的ID:

SELECT Invoices.Id, Invoices.Billing_date, Customers.Name, Referred_ID
    FROM Invoices 
    INNER JOIN Customers ON Invoices.Customer_Id = Customers.Id;

我应该如何修改查询以用其所有者名称替换Referred_ID?

顺便说一下,这是2015年的MySQL。

2 个答案:

答案 0 :(得分:1)

您可以使用别名使用两次的客户来加入推荐的客户

@RunWith(PowerMockRunner.class)
@PrepareForTest(XMLTransaction.class)
public class CloseSummaryOrCloseTrailerResponseTest {
    public final static String URL="WL_APPSERVER";
    private XMLTransaction xmlTransaction; 

    @Before
    public void initMocks() throws Exception {
        xmlTransaction = PowerMockito.spy(new XMLTransaction(URL)); 
        PowerMockito.doAnswer(new org.mockito.stubbing.Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                return null; //does nothing
            }
        }).when(xmlTransaction.getClass(), "initialize");
        PowerMockito.doNothing().when(xmlTransaction.getClass(), "initialize");             
    }

    @Test
    public void whenCloseSummaryResponseNoErrorExpectCorrectXmlMsgProduced () throws Exception
    {
    //set the mock object here
        try {                    
            String actualXmlScannerMsg = xmlTransaction.closeSummaryResponseToXMLNoErrors(mockCloseTrailerResponse);
            Assert.assertNotNull(actualXmlScannerMsg);
            Assert.assertEquals(msgNoCarReturnCharCloseSummaryResponse, actualXmlScannerMsg);   
        }
        catch(JsonProcessingException jEx)
        {
            Assert.fail("JsonProcessingException: " + jEx.getMessage());
        }
        catch(Exception ex)
        {
            Assert.fail("Exception occurred: " + ex.getMessage());
        }
    }
}

答案 1 :(得分:0)

在联接中两次使用“客户”表

 SELECT Invoices.Id, Invoices.Billing_date,
 c1.Name as customername,
c1.Referred_ID,
c2.Name as refername 
FROM Invoices INNER JOIN Customers c1 ON Invoices.Customer_Id = c1.Id
join Customers c2 on  c1.Id=c2.Referred_ID