下表包含每个都有invoiceID的付款交易。我正在尝试编写一个查询来列出与其关联的多个交易的invoiceID。
mysql> describe tblaccounts;
+-------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+----------------+
| id | int(10) | NO | PRI | NULL | auto_increment |
| userid | int(10) | NO | MUL | NULL | |
| date | datetime | YES | MUL | NULL | |
| description | text | NO | | NULL | |
| amount | decimal(10,2) | NO | | 0.00 | |
| transid | text | NO | MUL | NULL | |
| invoiceid | int(10) | NO | MUL | 0 | |
+-------------+---------------+------+-----+---------+----------------+
从我所读过的内容中我应该使用' GROUP BY'并且' HAVING'但我不明白如何使用它们。
答案 0 :(得分:1)
SELECT invoiceid
FROM tblaccounts
GROUP BY invoiceid HAVING COUNT(*)>1
你可以像这样使用。第一组按发票ID。现在我们有了具有相同invoiceid的组。然后,我们使用 HAVING 关键字选择计数多于一的组。有关详情,请点击此处:http://www.w3schools.com/sql/sql_having.asp和此处:http://www.w3schools.com/sql/sql_groupby.asp
答案 1 :(得分:0)
SELECT invoiceid FROM tblaccounts GROUP BY invoiceid HAVING COUNT(*) > 1