search

Home  >  Q&A  >  body text

What are the practical uses of MySQL's union query [union]?

What are the practical uses of MySQL’s union query [union]?

联合查询只要求两张表字段数一致,但是字段名却可以不同,能否提供一个使用它的例子?
曾经蜡笔没有小新曾经蜡笔没有小新2757 days ago1076

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-06-10 09:51:42

    The example used before has data from multiple information modules that need to be displayed. Each module table has a title, id, and picture fields. In order to reduce multiple SQL queries, use union to combine the data from these tables into a result set and return it.

    SELECT id,title,picture, 'A' AS module FROM A LIMIT 5
    UNION 
    SELECT id,title,picture, 'B' AS module FROM B LIMIT 5
    UNION
    SELECT id,title,picture, 'C' AS module FROM C LIMIT 5

    reply
    0
  • 巴扎黑

    巴扎黑2017-06-10 09:51:42

    For example, if you encounter a project with a large amount of data and need to divide it into tables. The same structure is divided into more than 100 tables, then when you query, you need to query each of these 100 tables and union all to obtain the data.

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-06-10 09:51:42

    Tips:

    select goods "商品", case goods when 1 then price then price*1.2 when 2 then price*1.5 else 0 end
    from talbe

    Disadvantage: poor code readability

    select goods, price*1.2
    from table where goods=1
    union
    select goods, price*1.5
    from table where goods=2
    union
    select goods, 0
    from table where goods not in (1, 2)

    Sometimes union can be used to solve some strange judgment statements. For example, returning the total of the report together

    reply
    0
  • Cancelreply