MySQL:枚举和计数

时间:2018-12-30 10:14:50

标签: mysql count enumerate

我有两个表table1table2

table1表的示例。

^ invoice ^ valid ^ 
| 10       | yes   | 
| 11       | yes   | 
| 12       | no    | 

table2表的示例

^ invoice ^ detail ^ 
| 10       | A      | 
| 10       | C      | 
| 10       | F      | 
| 11       | A      | 
| 11       | F      |
| 10       | E      | 
| 12       | A      | 

要从表2中选择以下所有行:

  • 表1中有有效发票

并列举:

  • 每张发票的详细信息
  • 发票

达到预期的效果

^ invoice ^ detail ^ ordination ^ ordinationb      ^ 
| 10       | A      |     1       |       1         | 
| 10       | C      |     2       |       1         |  
| 10       | F      |     3       |       1         |  
| 11       | A      |     1       |       2         |  
| 11       | F      |     2       |       2         | 
| 10       | E      |     4       |       1         | 

该句子应在phpMyAdmin 4.8.4中有效。

1 个答案:

答案 0 :(得分:3)

这是MySQL 8+的实现方法:

SELECT
    t2.Invoice,
    t2.`lines`,
    ROW_NUMBER() OVER (PARTITION BY t2.Invoice ORDER BY t2.`lines`) line_order,
    DENSE_RANK() OVER (ORDER BY t2.Invoice) ordination
FROM table2 t2
WHERE EXISTS (SELECT 1 FROM table1 t1 WHERE t1.Invoice = t2.Invoice AND t1.valid = 'yes');

enter image description here

Demo

如果您使用的MySQL版本早于8,则可能必须求助于使用会话变量。这可能导致难看的查询。如果您长期需要这种查询,那么我建议升级到MySQL 8 +。

编辑:

我突然意识到我们可以使用相关子查询来模拟您的ROW_NUMBERDENSE_RANK需求。这是在MySQL 5.7或更早版本中执行此查询的一种方法:

SELECT
    t2.Invoice,
    t2.detail,
    (SELECT COUNT(*) FROM table2 t
    WHERE t.Invoice = t2.Invoice AND t.detail <= t2.detail) ordination,
    t.dr AS ordinationb
FROM table2 t2
INNER JOIN
(
    SELECT DISTINCT
        t2.Invoice,
        (SELECT COUNT(*)
         FROM (SELECT DISTINCT Invoice FROM table2) t
         WHERE t.Invoice <= t2.Invoice) dr
    FROM table2 t2
) t
    ON t.Invoice = t2.Invoice
WHERE EXISTS (SELECT 1 FROM table1 t1 WHERE t1.Invoice = t2.Invoice AND t1.valid = 'yes')
ORDER BY
    t2.Invoice,
    t2.detail;

Demo