如何创建一个查询,从一个表中获取所有内容,然后加入另一个表,并将第二个表中的值放在结果中的某个列中
我所要求的可以更好地解释:
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 |
感谢
答案 0 :(得分:0)
您可以使用变量来检查最后一个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变量。在其他更复杂的案例中,您可能必须在单独的字段中执行此操作。但是要从结果中删除该占位符字段,您必须将整个查询嵌入到子选择中,并在顶级查询中按正确的顺序定义所需字段。
答案 1 :(得分:0)
您可以在clients_meta.meta_key中选择一个值,始终首先像'location'。然后你可以按clients.id排序,然后按meta_key ='location'排序。 meta_key!='location'的任何行都可以隐藏,如下所示:
select
case when clients_meta.meta_key = 'location'
then clients.id else '' end as id
, case when clients_meta.meta_key = 'location'
then clients.name else '' end as name
, case when clients_meta.meta_key = 'location'
then clients.age else '' end as age
, clients_meta.*
from clients join clients_meta on (clients_meta.client_id = clients.id)
where clients.age = '30'
order by clients.id, clients_meta.meta_key = 'location' desc;
您将获得所需的结果:
+------+-----------+------+----+-----------+----------+------------+
| id | name | age | id | client_id | meta_key | meta_value |
+------+-----------+------+----+-----------+----------+------------+
| 13 | ggggthing | 30 | 4 | 13 | location | TN |
| 15 | something | 30 | 1 | 15 | location | NY |
| | | | 3 | 15 | job | student |
| | | | 2 | 15 | height | 195 |
+------+-----------+------+----+-----------+----------+------------+