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 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频