1

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名称

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

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

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

可能在GROUP BY CompanyName某个地方需要。

请指教...

4

4 回答 4

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;
于 2013-08-08T09:24:19.977 回答
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;
于 2013-08-08T09:22:24.517 回答
1

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

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:更正列名。

于 2013-08-08T09:26:41.413 回答
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
于 2013-08-08T09:35:10.750 回答