在mysql

时间:2019-01-03 03:33:19

标签: php mysql group-concat

我有两个表:

表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
)

有什么办法可以做到这一点?感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

您的查询缺少GROUP BY子句,无法为每个用户获取一行。然后使用HAVING子句确保聚合行包含名字 '%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在MySQL中为1,在0中为false。因此,检查总和是否大于零意味着至少要检查一次该条件是否成立。