3

I'm having a problem in MySQL query.
I need MySQL query to display the following output and I also need to take CSV or Excel or PDF report.

Table1:

id | nos
-------------
1    12,13,14
2    14
3    14,12

Table2:

id | values
------------
12   raja
13   rames
14   ravi

I want output like this:

id | values
---------------------
1    raja, rames, ravi
2    ravi
3    ravi, raja
1
  • 1
    Can you change your schema to something more SQL-ish such as an association table instead of embedded CSV? Commented Nov 10, 2011 at 5:35

1 Answer 1

5

In SQL, it's better to store a single value in a column, not a comma-separated list of values. See my answer to Is storing a comma separated list in a database column really that bad?

You can try this query, but it will be terribly slow and inefficient:

SELECT Table1.id, GROUP_CONCAT(Table2.values) AS values
FROM Table1
JOIN Table2 ON FIND_IN_SET(Table2.id, Table1.nos)
GROUP BY Table1.id;

See the FIND_IN_SET() function.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks Bill Karwin for your valuable answer.. from this i got a idea to work in mysql...
hi Bill Karwin but the output seem to be change in order id | values --------------------- 1 ravi, rames, raja 2 ravi 3 ravi, raja
Look up the documentation on GROUP_CONCAT(). You can specify the sort order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.