我有一个多表查询,如下所示:
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')
因此,这为我提供了属于三个树条目中的任何一个的所有叶条目。
现在,我真的只想按照指定的顺序返回属于一棵树的叶条目。
因此,如果存在属于Poplar树的叶条目,则仅显示这些条目。但是,如果没有Poplar叶条目,则只显示属于Birch树的叶条目。
可能有任意数量的叶子条目。我只想要在我的优先级列表中出现的树上的那些。理想情况下只使用一个查询。
有什么想法吗?提前谢谢....
答案 0 :(得分: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;
答案 1 :(得分: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
答案 2 :(得分: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')