MySQL LEFT JOIN与DISTINCT或LIMIT。需要LEFT JOIN只有一个值

时间:2013-08-08 09:18:00

标签: mysql

MySQL表18_8_ChartOfAccounts

AccountNumber  | VatReturnRowNumberForDebitTurnover
-------------------------------------------
 1             | 61
 2             | 55

MySQL表2_1_journal

DebitAccount  | TransactionPartnerName | Amount
-----------------------------------------------
 1            |      Name1             | 55
 2            |      Name2             | 60

MySQL表18_6_TransactionPartners

CompanyName
-------------------------------
 Name1
 Name2
 Name1

查询

SELECT 
AccountNumber,
DebitAccount, TransactionPartnerName, Amount,
CompanyName
FROM 18_8_ChartOfAccounts
LEFT JOIN 2_1_journal
ON AccountNumber = DebitAccount
LEFT JOIN 18_6_TransactionPartners
ON TransactionPartnerName = CompanyName
WHERE VatReturnRowNumberForDebitTurnover = '61' AND Amount = 55

在获得这样的东西所需的输出

TransactionPartnerName | Amount
-----------------------------------------
  Name1                | 55

但是,如表18_6_TransactionPartners中有两个名称Name1 get

TransactionPartnerName | Amount
-----------------------------------------------
     Name1             | 55
     Name1             | 55

而不是SELECT尝试SELECT DISTINCT(相同的结果)。

而不是ON TransactionPartnerName = CompanyName尝试ON TransactionPartnerName = CompanyName LIMIT 1(获取语法错误)。

可能需要GROUP BY CompanyName某处。

请,建议......

4 个答案:

答案 0 :(得分:2)

DISTINCT不限制结果中的行数 - 它只是确保行都是唯一的。

LIMIT解决方案是正确的。只有它必须放在查询的末尾。所以正确的查询应该是:

SELECT 
    AccountNumber,
    DebitAccount, TransactionPartnerName, Amount,
    CompanyName
FROM 18_8_ChartOfAccounts
LEFT JOIN 2_1_journal
    ON AccountNumber = DebitAccount
LEFT JOIN 18_6_TransactionPartners
    ON TransactionPartnerName = CompanyName
WHERE VatReturnRowNumberForDebitTurnover = '61' AND Amount = 55
LIMIT 1;

答案 1 :(得分:1)

尝试这样的事情:

SELECT 
    TransactionPartnerName, Amount
FROM 18_8_ChartOfAccounts
    LEFT JOIN 2_1_journal ON AccountNumber = DebitAccount
    LEFT JOIN 18_6_TransactionPartners ON TransactionPartnerName = CompanyName
WHERE VatReturnRowNumberForDebitTurnover = '61' AND Amount = 55
GROUP BY TransactionPartnerName;

答案 2 :(得分:1)

您可以在LEFT JOIN的子查询中使用group by-statement for TransactionPartners表。

SELECT 
    AccountNumber, DebitAccount, TransactionPartnerName, Amount, CompanyName
FROM 18_8_ChartOfAccounts
    LEFT JOIN 2_1_journal ON AccountNumber = DebitAccount
    LEFT JOIN (SELECT CompanyName FROM 18_6_TransactionPartners GROUP BY CompanyName) ON TransactionPartnerName = CompanyName
WHERE VatReturnRowNumberForDebitTurnover = '61' AND Amount = 55

edit1 :更正后的列名。

答案 3 :(得分:0)

尝试使用唯一键在表之间建立关系。

将TransactionPartnerName更改为TransactionPartnerId并将新列PartnerId添加到18_6_TransactionPartners表,然后使用此新列连接这些表。

SELECT AccountNumber, DebitAccount, TransactionPartnerName, Amount, CompanyName 
FROM 18_8_ChartOfAccounts 
    LEFT JOIN 2_1_journal ON AccountNumber = DebitAccount 
    LEFT JOIN 18_6_TransactionPartners ON TransactionPartnerId = PartnerId 
WHERE VatReturnRowNumberForDebitTurnover = '61' AND Amount = 55