如何在表格中查询表格?

内塔·梅塔(Neta Meta)

我该如何进行查询,从一个表中获取所有内容,然后联接另一个表,并将第二个表中的值放在结果的某个列中

我在问什么可以更好地解释:

clients:
id | name      | age | ...
---------------------
15 | something | 30  |
17 | somethiaa | 30  |
13 | ggggthing | 30  |

clients_meta:
id | client_id | meta_key  | meta_value |
-----------------------------------------
1  | 15        | location  | NY         |
2  | 15        | height    | 195        |
3  | 15        | job       | student    |
4  | 13        | location  | TN         |

这是我当前的查询:

SELECT
`clients`.*,
`clients_meta`.*

FROM `clients`

JOIN clients_meta ON ( clients_meta.client_id = clients.id )

WHERE
`clients_age` = '30'

怎么能代替像这样的丑陋的桌子:

15 | something | 30  | 1  | 15        | location  | NY         |
15 | something | 30  | 2  | 15        | height    | 195        |
15 | something | 30  | 3  | 15        | job       | student    |

将其更改为:

15 | something | 30  | 1  | 15        | location  | NY         |
                     | 2  | 15        | height    | 195        |
                     | 3  | 15        | job       | student    |

谢谢

GolezTrol

您可以使用变量来检查最后一个ID是否等于当前ID,在这种情况下,输出null或''。

select
  case when c.ClientId <> @clientid then c.Name else '' end as ClientName,
  case when c.ClientId <> @clientid then @ClientId := c.ClientId else '' end as ClientId,
  p.ContactId,
  p.Name as ContactName
from
  Clients c
  inner join Contacts p on p.ClientId = c.Clientid
  , (select @clientid := -1) x
order by
  c.ClientId, p.ContactId

示例:http//sqlfiddle.com/#!2 / 658e4c / 6

注意,这有点hacky。我故意将ClientId设置为第二个字段,因此可以在同一字段中更改并返回clientId变量。在其他更复杂的情况下,您可能必须在单独的字段中执行此操作。但是要从结果中删除该占位符字段,您必须将整个查询嵌入子选择中,并在顶层查询上以正确的顺序定义所需的字段。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章