小编典典

MySQL JOIN-左表中的重复结果返回NULL

sql

我相信这是一件非常简单的事情,我发誓我以前做过,但是我不记得怎么做。

假设我有一对多的关系。我想加入两个表,但不允许左侧表重复。

SQLFIDDLE

因此,根据上述SQLFiddle,我的结果将是:

categories.title  |  items.NAME  |  items.category_id
-----------------------------------------------------
red               | apple        | 1
red               | car          | 1
red               | paper        | 1
yellow            | lego         | 2
yellow            | banana       | 2
blue              | pen          | 3

我希望它是:

categories.title  |  items.NAME  |  items.category_id
-----------------------------------------------------
red               | apple        | 1
NULL              | car          | 1
NULL              | paper        | 1
yellow            | lego         | 2
NULL              | banana       | 2
blue              | pen          | 3

我的理由是,通过这种方式,我可以轻松地遍历结果,而无需使用PHP进行任何进一步处理。


阅读 183

收藏
2021-04-14

共1个答案

小编典典

您可以将值替换为以下内容:

select 
  case when rownum = 1 then title else null end title,
  name,
  category_id
from
(
  SELECT c.title, 
    i.name, 
    i.category_id,
    @row:=(case when @prev=title and @precat=category_id 
           then @row else 0 end) + 1 as rownum,
    @prev:=title ptitle,
    @precat:=category_id pcat
  FROM items AS i
  INNER JOIN categories AS c 
    ON c.id = i.category_id
   order by i.category_id, c.title
) src
order by category_id, rownum

参见带有演示的SQL Fiddle

结果是:

|  TITLE |   NAME | CATEGORY_ID |
---------------------------------
|    red |  apple |           1 |
| (null) |    car |           1 |
| (null) |  paper |           1 |
| yellow |   lego |           2 |
| (null) | banana |           2 |
|   blue |    pen |           3 |
2021-04-14