1

I have a multiple table query that looks something like:

SELECT tree.name, tree.type, branch.name, branch.type, leaf.name, leaf.type 
FROM tree, branch, leaf 
WHERE leaf.branch_id = branch.id 
   AND branch.tree_id = tree.id
ORDER by field(tree.type, 'Poplar', 'Birch', 'Hazelnut')

So this gives me all leaf entries that belong to any of the three tree entries.

Now, I would really only like to return the leaf entries that belong to ONE tree, in the order specified.

So if there are leaf entries belonging to a Poplar tree, only display these. However, if there are no Poplar leaf entries, only display leaf entries belonging to the Birch tree.

There could be any number of leaf entries. I just want the ones on a tree that appears in my priority list. Ideally just using one query.

Any ideas? Thanks in advance....

4

3 回答 3

0

尝试这个:

SELECT * FROM
(
    SELECT tree.name, tree.type, branch.name, branch.type, leaf.name, leaf.type, 
           IF(@var_type = '' OR a.type = @var_type, a.type := @var_type, 0) AS check_flag
    FROM tree, branch, leaf, (SELECT @var_type := '')
    WHERE leaf.branch_id = branch.id
          AND branch.tree_id = tree.id
    ORDER by field(tree.type, 'Poplar', 'Birch', 'Hazelnut')
) a
WHERE check_flag <> 0;
于 2012-08-16T10:47:28.370 回答
0

我建议使用http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set

有了它,你可以做到

    SELECT * FROM (
    SELECT find_in_set(tree.type, "Poplar,Birch,Hazelnut") as sequence, tree.name, tree.type,    branch.name, branch.type, leaf.name, leaf.type 
    FROM tree, branch, leaf 
    WHERE leaf.branch_id = branch.id 
       AND branch.tree_id = tree.id
    ORDER by sequence
    ) WHERE sequence = 1
于 2012-08-16T10:50:09.000 回答
0

这是一种方法。此查询首先为每个叶子找到适当的树类型。然后它将这些信息重新加入:

select tree.name, tree.type, branch.name, branch.type, leaf.name, leaf.type
from (SELECT leaf.id,
             min(case when tree.type = 'Poplar' then tree.id end) as poplarid,
             min(case when tree.type = 'Birch' then tree.id end) as birchid,
             min(case when tree.type = 'Hazelnut' then tree.id end) as hazelid
      FROM leaf join
           branch
           on leaf.branch_id = branch.id join
           tree
           on branch.tree_id = tree.id join
      group by leaf.id
     ) lt join
     leaf
     on leaf.leaf_id = lt.leaf_id join
     branch
     on leaf.branch_id = branch.id join
     tree
     on tree.id = branch.tree_id
where tree.id = coalesce(lt.poplarid, lt.birchid, lt.hazelid)
ORDER by field(tree.type, 'Poplar', 'Birch', 'Hazelnut')
于 2012-08-16T10:51:38.890 回答