select GROUP_CONCAT 在 mysql

select GROUP_CONCAT in mysql

我有两个表:

表 1:

id email
1  john@gmail.com
2  doe@gmail.com

表 2:

userid   key         value
1        firstname   john
1        phone       112233
2        firstname   doe
2        phone       223344

这是mysql无条件查询:

SELECT a.*,
b.*,
GROUP_CONCAT(b.key),
GROUP_CONCAT(b.value)
FROM table1 a
LEFT JOIN table2 b ON a.id = b.userid

这是结果:

array(
[id] => 1
[email] => john@gmail.com
[userid] => 1
[key] => firstname,phone
[value] => john,112233
)
array(
[id] => 2
[email] => doe@gmail.com
[userid] => 2
[key] => firstname,phone
[value] => doe,223344
)

这是 mysql 条件查询:

SELECT a.*,
b.*,
GROUP_CONCAT(b.key),
GROUP_CONCAT(b.value)
FROM table1 a
LEFT JOIN table2 b ON a.id = b.userid
WHERE b.key = "firstname"
  AND b.value LIKE '%jo%'

这是结果:

array(
[id] => 1
[email] => john@gmail.com
[userid] => 1
[key] => firstname
[value] => john
)

但我想要这个:

array(
[id] => 1
[email] => john@gmail.com
[userid] => 1
[key] => firstname,phone
[value] => john,112233
)

有什么办法吗?感谢您的帮助!

您的查询缺少 GROUP BY 子句来为每个用户获取一行。然后使用 HAVING 子句确保聚合行包含 firstname '%jo%':

SELECT a.*,
       GROUP_CONCAT(b.key),
       GROUP_CONCAT(b.value)
FROM table1 a
LEFT JOIN table2 b ON a.id = b.userid
GROUP BY a.id
HAVING sum(b.key = 'firstname'
           AND b.value LIKE '%jo%') > 0;

true 结果为 1,false 结果为 0 MySQL。所以检查和是否大于零意味着至少检查一次条件是否为真。