How to display database records in the view without repeating a field?

后端 未结 2 723
独厮守ぢ
独厮守ぢ 2021-01-22 18:57

In my database I have two tables one politics (politics_id, politics, politics_type_id) and other tipo_politics (politics_type_id, politics_type).
This is the table

2条回答
  •  礼貌的吻别
    2021-01-22 19:22

    If you make a query like this, then you'll get a row for the type as well as the actual politics:

    select tp.politics_type_id, tp.politics_type politics_text, null politics_id,  1 row_type
    from tipo_politics tp
    union
    select p.politics_type_id, p.politics politics_text, p.politics_id, 2 row_type
    from politics p
    order by politics_type_id, row_type, politics_id;
    

    This gives results like this:

    +------------------+---------------+-------------+----------+
    | politics_type_id | politics_text | politics_id | row_type |
    +------------------+---------------+-------------+----------+
    |                1 | general       |             |        1 |
    |                1 | Politic 1     |           1 |        2 |
    |                1 | magic         |           3 |        2 |
    |                1 | love          |           4 |        2 |
    |                2 | life          |             |        1 |
    |                2 | hello world   |           2 |        2 |
    +------------------+---------------+-------------+----------+
    

    Now you can loop through the results, and only act on the header rows (where row_type = 1). Then within that loop, do another loop and pick out the detail rows (where row_type = 2).

    
       

提交回复
热议问题