SQL选择一对多

我想不出任何关于此事的术语,而是将您要显示的表格提供给您。

Table 1
ID | Product | Description
1  | Dell    | Dell Laptop

Table 2
ID | ProductID | Attribute | Description
1  | 1         | Processor | i7
2  | 1         | USB 3.0   | USB 3.0 Descript

使用join,我可以显示如下结果:

Product | Attribute | Description
Dell    | Processor | i7
Dell    | USB 3.0   | USB 3.0 Descript

我想展示的是这样的。

Product | Attribute | Description
Dell    | Processor | i7
        | USB 3.0   | USB 3.0 Descript

如果表2的ProductID与上一行的上一个ProductID相同,则该产品名称仅显示一次。如何仅使用SQL做到这一点?

足球迷

就像上面提到的@GordonLinoff一样,这应该在应用程序端完成,而不是使用SQL。您可以在MySQL中执行以下操作:

SET @row_number := 0 ;
SET @productnames:='';

SELECT 
    CASE 
      WHEN num = 1
          THEN t.Product
    ELSE '' 
    END Product,
    t.Attribute,
    t.Description
FROM
(SELECT 
    @row_number:=CASE WHEN @productnames=t1.product 
                       THEN @row_number+1 
                     ELSE 1 END AS num,
    @productnames:=t1.product AS product,
    t2.Attribute,
    t2.Description
from table1 t1
inner join table2 t2 on t1.ID = t2.ProductID
) t;

SQL小提琴演示

这里的技巧是分配一个伪造的row_number,然后仅Product在row_number = 1时使用一条case when语句填充该希望这可以帮助!

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章