与上一行比较,如果值相同,则留空

时间:2018-12-10 10:01:18

标签: mysql

此刻我有以下问题。

我有一张桌子,例如,我从中获得了旅行的名字,并且我有一个子表,其中有多于一行与旅行相关的信息,表的旅程。

我想要得到什么:

+---+------------+-------------+-------------+
|   |  Name      |   Subname   |   Info Sub  |
+---+------------+-------------+-------------+
| 1 | Tour 1     | Journey 1   | duration,km |
| 2 |            | Journey 2   | duration,km |
| 3 |            | Journey 3   | duration,km |
| 4 | Tour 2     | Journey 1   | duration,km |
| 5 |            | Journey 2   | duration,km |
| 6 | Tour 3     | Journey 1   | duration,km |
+---+------------+-------------+-------------+

我已经尝试过的东西:

SELECT 
if (t.id = @tid,"",(SELECT tourname FROM tours WHERE id = @tid)),
tj.journeyname,
if(@tid != t.id, @tid := t.id,"")
FROM tours t 
JOIN tours_journeys tj ON tj.toursid = t.id ORDER BY t.id

似乎在完成选择之前已分配@tid,因此在最后一行中使用相同的旅游名称再次打印旅游名称。如果有人知道该怎么做,那就太好了。 :)

1 个答案:

答案 0 :(得分:0)

您可以使用子查询来实现。这样可以按照以下正确顺序对结果进行排序,以使用 IF

SELECT  
    IF(result.id = @myg, '', @myg:= result.id) AS gname,
    result.*
FROM (
    SELECT 
        t.id,
        tj.journeyName
    FROM tours t
    JOIN tour_journeys tj ON tj.tour_id = t.id
    CROSS JOIN ( SELECT   @myg:='') AS init
    ORDER BY t.id, tj.id
) result;

样品

MariaDB [test]> SELECT
    ->     IF(result.id = @myg, '', @myg:= result.id) AS gname,
    ->     result.*
    -> FROM (
    ->     SELECT
    ->         t.id,
    ->         tj.journeyName
    ->     FROM tours t
    ->     JOIN tour_journeys tj ON tj.tour_id = t.id
    ->     CROSS JOIN ( SELECT   @myg:='') AS init
    ->     ORDER BY t.id, tj.id
    -> ) result;
+-------+------+-------------+
| gname | id   | journeyName |
+-------+------+-------------+
| 1     |    1 | journey 1   |
|       |    1 | journey 2   |
|       |    1 | journey 3   |
|       |    1 | journey 4   |
|       |    1 | journey 5   |
|       |    1 | journey 6   |
| 2     |    2 | journey 1   |
|       |    2 | journey 2   |
+-------+------+-------------+
8 rows in set (0.006 sec)

MariaDB [test]>