gpt4 book ai didi

mysql - 如何根据另一列的值获取单行值?

转载 作者:太空宇宙 更新时间:2023-11-03 11:33:11 26 4
gpt4 key购买 nike

我正在尝试根据 name 列中的值从 value 列中选择值。

例如:

mysql> select name, value from rss_feed_property_value where rss_feed_id = 31;
+-------------+---------------+
| name | value |
+-------------+---------------+
| High | 45 |
| Description | Rain And Snow |
| Low | 25 |
| Day | Fri |
| Date | 29 Dec 2017 |
+-------------+---------------+
5 rows in set (0.00 sec)

我几乎通过以下查询实现了这一目标:

select

if (rfpv.name = 'Date', rfpv.value, null) as `Date`,
if (rfpv.name = 'High', rfpv.value, null) as `High`,
if (rfpv.name = 'Low', rfpv.value, null) as `Low`,
if (rfpv.name = 'Description', rfpv.value, null) as `Description`

from rss_feed rf
join rss_feed_definition rfd on rf.rss_feed_definition_id = rfd.id
join rss_feed_property_value rfpv on rfpv.rss_feed_id = rf.id

where rfd.type = 'weather'
and rf.id = 31
order by rf.id;

产生以下输出:

+-------------+------+------+---------------+
| Date | High | Low | Description |
+-------------+------+------+---------------+
| NULL | 45 | NULL | NULL |
| NULL | NULL | NULL | Rain And Snow |
| NULL | NULL | 25 | NULL |
| NULL | NULL | NULL | NULL |
| 29 Dec 2017 | NULL | NULL | NULL |
+-------------+------+------+---------------+
5 rows in set (0.00 sec)

我现在如何通过忽略空值只留下一行来使上面的内容变平,如下所示:

+-------------+------+------+---------------+
| Date | High | Low | Description |
+-------------+------+------+---------------+
| 29 Dec 2017 | 45 | 25 | Rain and Snow |
+-------------+------+------+---------------+

最佳答案

通过 rf.id 聚合并使用条件聚合。我会在这里使用 CASE 表达式,因为与 MySQL 的 IF 相比,这种语法在数据库中得到更广泛的支持。

SELECT
rf.id,
MAX(CASE WHEN rfpv.name = 'Date' THEN rfpv.value END) AS Date,
MAX(CASE WHEN rfpv.name = 'High' THEN rfpv.value END) AS High,
MAX(CASE WHEN rfpv.name = 'Low' THEN rfpv.value END) AS Low,
MAX(CASE WHEN rfpv.name = 'Description' THEN rfpv.value END) AS Description
FROM rss_feed rf
INNER JOIN rss_feed_definition rfd
ON rf.rss_feed_definition_id = rfd.id
INNER JOIN rss_feed_property_value rfpv
ON rfpv.rss_feed_id = rf.id
WHERE
rfd.type = 'weather' AND
rf.id = 31
GROUP BY
rf.id
ORDER BY
rf.id;

关于mysql - 如何根据另一列的值获取单行值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48033924/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com