mysql 由价格1,价格2,价格3到价格10字段,判断不为0的值的两个字段,中间为0值用第二个不为0的值填充
时间: 2024-03-22 13:41:54 浏览: 54
mysql判断字段是否存在的方法
你可以使用MySQL中的CASE语句来实现该功能。具体步骤如下:
1. 使用CASE语句判断价格1到价格10中不为0的字段,并按照顺序将它们存储在一个数组中,例如:
```
SELECT
CASE
WHEN 价格1 != 0 THEN 价格1
WHEN 价格2 != 0 THEN 价格2
WHEN 价格3 != 0 THEN 价格3
WHEN 价格4 != 0 THEN 价格4
WHEN 价格5 != 0 THEN 价格5
WHEN 价格6 != 0 THEN 价格6
WHEN 价格7 != 0 THEN 价格7
WHEN 价格8 != 0 THEN 价格8
WHEN 价格9 != 0 THEN 价格9
ELSE 价格10
END AS prices
FROM your_table;
```
2. 使用MySQL中的GROUP_CONCAT函数将不为0的价格字段拼接成一个字符串,例如:
```
SELECT
GROUP_CONCAT(prices SEPARATOR ',') AS price_str
FROM (
SELECT
CASE
WHEN 价格1 != 0 THEN 价格1
WHEN 价格2 != 0 THEN 价格2
WHEN 价格3 != 0 THEN 价格3
WHEN 价格4 != 0 THEN 价格4
WHEN 价格5 != 0 THEN 价格5
WHEN 价格6 != 0 THEN 价格6
WHEN 价格7 != 0 THEN 价格7
WHEN 价格8 != 0 THEN 价格8
WHEN 价格9 != 0 THEN 价格9
ELSE 价格10
END AS prices
FROM your_table
) AS temp;
```
3. 使用MySQL中的SUBSTRING_INDEX函数将字符串按照逗号分割成数组,例如:
```
SELECT
SUBSTRING_INDEX(price_str, ',', 1) AS price1,
SUBSTRING_INDEX(SUBSTRING_INDEX(price_str, ',', 2), ',', -1) AS price2,
SUBSTRING_INDEX(SUBSTRING_INDEX(price_str, ',', 3), ',', -1) AS price3,
SUBSTRING_INDEX(SUBSTRING_INDEX(price_str, ',', 4), ',', -1) AS price4,
SUBSTRING_INDEX(SUBSTRING_INDEX(price_str, ',', 5), ',', -1) AS price5,
SUBSTRING_INDEX(SUBSTRING_INDEX(price_str, ',', 6), ',', -1) AS price6,
SUBSTRING_INDEX(SUBSTRING_INDEX(price_str, ',', 7), ',', -1) AS price7,
SUBSTRING_INDEX(SUBSTRING_INDEX(price_str, ',', 8), ',', -1) AS price8,
SUBSTRING_INDEX(SUBSTRING_INDEX(price_str, ',', 9), ',', -1) AS price9,
SUBSTRING_INDEX(SUBSTRING_INDEX(price_str, ',', 10), ',', -1) AS price10
FROM (
SELECT
GROUP_CONCAT(prices SEPARATOR ',') AS price_str
FROM (
SELECT
CASE
WHEN 价格1 != 0 THEN 价格1
WHEN 价格2 != 0 THEN 价格2
WHEN 价格3 != 0 THEN 价格3
WHEN 价格4 != 0 THEN 价格4
WHEN 价格5 != 0 THEN 价格5
WHEN 价格6 != 0 THEN 价格6
WHEN 价格7 != 0 THEN 价格7
WHEN 价格8 != 0 THEN 价格8
WHEN 价格9 != 0 THEN 价格9
ELSE 价格10
END AS prices
FROM your_table
) AS temp
) AS temp2;
```
以上代码可以将不为0的价格字段存储在对应的price1到price10中,并用第二个不为0的值填充中间的0值。注意,以上代码中的your_table需要替换为你的表名。
阅读全文