douluanzhao6689 2016-08-29 18:04
浏览 30
已采纳

MySQL - 来自行的PHP唯一值

I have this table: table 1

+----+-----------------------+----------+------+-------+
| ID | COUNTRY               | QUANTITY | EACH | PRICE |
+----+-----------------------+----------+------+-------+
| 1  | U.S.A                 |     1    |  12  | 1*12  |
| 2  | U.K.                  |     2    |   3  | 2* 3  |
| 3  | GERMANY               |   NULL   |   3  |       |
| 4  | FRANCE;GERMANY; U.S.A |     0    |   7  |       |
| 5  | U.S.A;GERMANY         |     3    |   8  | 3*8   |
| 6  | FRANCE;U.K.           |     1    |  10  | 1*10  |
| 7  | U.S.A;FRANCE          |     2    |   6  | 2*6   |
| 8  | FRANCE;FRANCE         |     9    |   3  | 9*3   |
+----+-----------------------+----------+------+-------+

and this code sql:

SELECT
  COUNTRY,
  SUM(COALESCE(IF(QUANTITY = NULL OR QUANTITY = 0,1,QUANTITY), 1) * EACH) AS PRICE
FROM table1
GROUP BY COUNTRY

How could I make unique values for the country column and return: USA = 48 (ID: 1+5+7); UK= 6; GERMANY=3; FRANCE = 44 (ID: 4+6+8). I want that the rows, those contain two, three, four countries to be eliminated and to remain only the first country from row. Thank you!

</div>
  • 写回答

1条回答 默认 最新

  • donglan9651 2016-08-29 18:37
    关注

    Use substring_index to get the first country in the ;-separated list.

    SELECT
      SUBSTRING_INDEX(COUNTRY, ';', 1) AS COUNTRY
      SUM(IF(QUANTITY IS NULL OR QUANTITY = 0,1,QUANTITY) * EACH) AS PRICE
    FROM table1
    GROUP BY COUNTRY
    

    It would be much more complicated if you wanted to keep all the rows where each country appears (in that case I would recommend doing it in PHP, not MySQL, since MySQL doesn't have a builtin way to do explode()).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?