1

I have the following tables :

specifications :

id | name
-----------
1  | hello
2  | world
3  | foo
4  | bar

properties :

name   | value  | specID
---------------------
status | finish | 1
parent | 2      | 1
status | work   | 2
parent | 3      | 2
status | ...    | 4
parent | 3      | 4

Now I want to say :

List all specifications under specID 3.

I don't now the levels down but the result must be:

id | name  | parent
------------------
 3 | foo   |  NULL
 2 | world | 3
 1 | hello | 2
 4 | bar   | 3

How can i do this in mysql?

Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
Alexander G.
  • 333
  • 1
  • 4
  • 15

3 Answers3

1

Try this:

SELECT s.id, s.name, p.value AS parent
FROM specifications s 
LEFT JOIN properties p ON s.id = p.specID AND p.name = 'parent'; 
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
1

You can try it like this

SELECT 
    s.id,
    s.name,
    IFNULL(p.value,0) as parent
FROM  specifications s
LEFT JOIN properties p 
    ON p.specID = s.id 
    AND p.name  ='parent'
ORDER BY parent 

Output

| ID |  NAME | PARENT |
|----|-------|--------|
|  3 |   foo |      0 |
|  1 | hello |      2 |
|  2 | world |      3 |
|  4 |   bar |      3 |

Fiddle

Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
1

MySQL does not have any syntax constructs that allow you to write a recursive query. So, with this schema, there is no convenient way to retrieve a full tree - at least, not with a SELECT query.

What you could do is try to rework your schema to a "materialized path", or a "nested set" or a "nested interval" solution. See these papers for details:

http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ http://sigmod.acm.org/publications/sigmod-record/0506/p47-article-tropashko.pdf

Roland Bouman
  • 31,125
  • 6
  • 66
  • 67