用select填充值

qybjjes1  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(293)

更新:下面是问题的演示:http://www.sqlfiddle.com/#!9/15ff5e/1号
我正在尝试对以下两个表执行左联接:

post_metrics

| post_id | likes |
|---------|-------|
| 'aaa'   |     3 |
| 'aaa'   |     7 |
| 'aaa'   |     8 |
| 'bbb'   |     2 |
| 'bbb'   |     4 |

post_history

| post_id | post_text |
|---------|-----------|
| 'aaa'   | 'doug'    |
| 'bbb'   | 'steve'   |

结果如下:

| post_id | likes | post_text |
|---------|-------|-----------|
| 'aaa'   |     3 | 'doug'    |
| 'aaa'   |     7 | NULL      |
| 'aaa'   |     8 | NULL      |
| 'bbb'   |     2 | 'steve'   |
| 'bbb'   |     4 | NULL      |

我想用前几行的数据填充这些空值,结果如下:

| post_id | likes | post_text |
|---------|-------|-----------|
| 'aaa'   |     3 | 'doug'    |
| 'aaa'   |     7 | 'doug'    |
| 'aaa'   |     8 | 'doug'    |
| 'bbb'   |     2 | 'steve'   |
| 'bbb'   |     4 | 'steve'   |

但是,我使用的查询。。。

SELECT m.id,
       m.likes,
       @username := ifnull(p.username, @username) as username
FROM (select * from `post_metrics` WHERE post_id = @post_id) AS m
LEFT JOIN `post_history` AS p ON (m.post_id = p.post_id)

…给了我以下结果:

| post_id | likes | post_text |
|---------|-------|-----------|
| 'aaa'   |     3 | 'doug'    |
| 'aaa'   |     7 | 'steve'   |
| 'aaa'   |     8 | 'steve'   |
| 'bbb'   |     2 | 'steve'   |
| 'bbb'   |     4 | 'steve'   |

如何正确填充前几行的空值?
这些表有数百万行和大约6列稀疏的空值要填充。对于每个post\u id,'post\u text'字段并不总是相同的(偶尔会有变化),因此我需要将这些更改传播到以下具有null的行。

rjee0c15

rjee0c151#

现有查询的问题是 @username 基于查询的无序行输出计算。所以你需要先对数据进行排序,然后再进行 username 替换(或者,根据你的sqlfiddle, post_text ). 所以我认为这个查询应该满足您的要求:

SELECT post_id, 
       date, 
       likes,
       @post_text := COALESCE(post_text, @post_text) AS post_text
FROM (SELECT 
       m.post_id,
       m.date,
       m.likes,
       p.post_text 
      FROM `post_metrics` m
      LEFT JOIN `post_history` AS p ON m.post_id = p.post_id and m.date = p.date
      ORDER BY m.post_id, m.date) o
JOIN (SELECT @post_text := '') t

输出:

post_id     date        likes   post_text
aaa         2018-09-01  3       ccccc
aaa         2018-09-02  7       ccccc
aaa         2018-09-03  8       ccccd
bbb         2018-09-01  2       eeeee
bbb         2018-09-02  4       eeeee

sqlfiddle演示

ukqbszuj

ukqbszuj2#

尝试下面使用内部连接

SELECT m.id,
       m.likes,
       m.username 
       from `post_metrics`  m
inner JOIN `post_history` AS p ON m.post_id = p.post_id

相关问题