GROUP_CONCAT与WHERE IN子句

时间:2018-04-19 23:52:36

标签: mysql group-concat

我正在尝试将具有特定匹配字符串的多个列组合在一起。

SELECT GROUP_CONCAT(`users`.`id`) 
FROM `users` 
WHERE `users`.`name`
IN ('john','doe','foo','bar');

我没有收到错误,只是结果是NULL,即使表中有所有这些名称的列。

如何构建查询以实现预期结果?

1 个答案:

答案 0 :(得分:0)

Q: How do I structure my query to accomplish the expected outcome?

A: Backup to the previous query, the one that was working, and returning expected results. And then figure out why the change you made to that query caused the unintended behavior/unexpected results.

For example, likely you started writing the query like this:

SELECT u.id
     , u.name 
  FROM users u
 ORDER
    BY u.name 

And you ran that to test it, and verify that it returned expected results. Is id non-NULL. Is name column populated?

Next, you added WHERE clause, to see if you could get rows that had a name column containing 'john'.

SELECT u.id
     , u.name 
  FROM users u
 WHERE u.name = 'john'
 ORDER
    BY u.name

Did that return expected results when you ran that? If not, we need to figure out why not. What's different about that query than the one that was working.

How far did we get with this stepwise refinement, in writing the query, before we got to a query that is returning unexpected results? Show us that.

And then explain why a change made to that query, into a different query, should produce a particular result. i.e. what results are the "expected outcome". And Why is that outcome expected?


Absent a specification, it's impossible to make any recommendations. Sample data and example output would go a long ways towards clarifying the requirements. You might even go so far as setting up a SQLFiddle example.

If you are asking a busy colleague for help, it behooves you to show some work, how far you got. Rather than just "here's a query that doesn't work".

https://ericlippert.com/2014/03/05/how-to-debug-small-programs/


Otherwise, we're just guessing at what result you are expecting to be returned.

Maybe the answer is as simple as wrapping an expression in an IFNULL

SELECT IFNULL( GROUP_CONCAT(foo) ,'')  AS bar
     , 

But we are likely barking guesses up the entirely wrong tree.

相关问题