What are the practical uses of MySQL's union query [union]?
曾经蜡笔没有小新
曾经蜡笔没有小新 2017-06-10 09:49:42
0
3
1009

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

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

reply all(3)
Ty80

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
巴扎黑

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.

我想大声告诉你

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!