MySQL的聯合查詢[union]有什么實際的用處
問題描述
MySQL的聯合查詢[union]有什么實際的用處?
聯合查詢只要求兩張表字段數一致,但是字段名卻可以不同,能否提供一個使用它的例子?
問題解答
回答1:之前使用的例子,有多個信息模塊的數據,需要展示,每個模塊表都有一個title,id,picture字段。為減少多次的查詢SQL,使用union將這些表的數據合為一個結果集返回。
SELECT id,title,picture, ’A’ AS module FROM A LIMIT 5UNION SELECT id,title,picture, ’B’ AS module FROM B LIMIT 5UNIONSELECT id,title,picture, ’C’ AS module FROM C LIMIT 5回答2:
比如說遇到一個項目,數據量超大,需要分表,同樣的結構分了100多個表,那么去查詢的時候需要這100個表中分別進行查詢并 union all 來獲取數據。
回答3:小技巧:
select goods '商品', case goods when 1 then price then price*1.2 when 2 then price*1.5 else 0 endfrom talbe
缺點:代碼可讀性差
select goods, price*1.2from table where goods=1unionselect goods, price*1.5from table where goods=2unionselect goods, 0from table where goods not in (1, 2)
有時候利用union可以解決一些奇怪的判斷語句.比如將報表的合計一起返回
相關文章:
1. 關于docker下的nginx壓力測試2. angular.js - angularjs的自定義過濾器如何給文字加顏色?3. angular.js使用$resource服務把數據存入mongodb的問題。4. docker-machine添加一個已有的docker主機問題5. docker安裝后出現Cannot connect to the Docker daemon.6. 為什么我ping不通我的docker容器呢???7. docker - 如何修改運行中容器的配置8. nignx - docker內nginx 80端口被占用9. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題10. docker鏡像push報錯
