Question

flat-on-desk day.

I'm trying to retrieve data in a pre-sorted format from the following, within a MySQL 5.1 database:

id | name    | sub
-------------------
1  | cat 1   | 0
2  | cat 2   | 0
3  | cat 3   | 0
4  | sub 1   | 2

The 'sub' column above refers to the id of the same table, but as a sub category grouping. I want to be able to essentially export the list, using CONCAT() only when it is a sub category.

Ideally, the final output would be this:

id | name
------------------
1  | cat 1
2  | cat 2
4  | cat 2 - sub 1
3  | cat 3

My feeble attempts have led me to this hilarious query, to no avail:

SELECT c.id AS id,
(case when c.sub > 0 then CONCAT(ca.name, ' - ', c.name) AS name else c.name AS name)
FROM cat c
LEFT JOIN cat ca ON c.sub = ca.id
ORDER BY name ASC

Any help would be rewarded with undeniable gratitude, and potentially cookies.

Était-ce utile?

La solution

What is needed here is to LEFT JOIN the table against itself to get the category and the sub-category. The COALESCE() returns either the concatenated value (which is NULL if there's no matching sub-category) or the concatenated value.

SELECT
  s.id,
  COALESCE(CONCAT(c.name, '-', s.name), s.name) AS catname
FROM
  cats s
  LEFT JOIN cats c ON s.sub = c.id
ORDER BY catname ASC

Here is an example: http://sqlfiddle.com/#!2/201b1/8

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top