如何组合两个mysql查询以在一个下拉列表中显示其结果

时间:2017-02-24 12:40:38

标签: php mysql union

我有两个表类别和子类别。在类别表中,我有一列cat_url.In子类别表,我有一列sub_cat_url

我想要的是获取按字母顺序排序的类别表和子类别表的所有URL并在菜单下拉菜单中显示

我在做的是:

$A = "SELECT cat_url FROM category
WHERE cat_url like 'a%'

UNION ALL

SELECT sub_cat_url FROM subcategory
WHERE sub_cat_url like 'a%'
ORDER BY cat_url, sub_cat_url";

$rA = mysqli_query($dbc,$A) or die(mysqli_error($dbc));

while ($rsA = mysqli_fetch_assoc($rA)){ 

    <a href=".$rsA['cat_url'].'.php'.">

    echo $rsA['cat_url']; 

    // i do not want to use $rsA['cat_url']; What i need is to combine both cat_url and sub_cat_url in one result set and the echo each url

} 

2 个答案:

答案 0 :(得分:1)

尝试以下查询:

select *
  from (
    SELECT cat_url as url FROM category WHERE cat_url like 'a%' 
    union all
    SELECT sub_cat_url as url FROM subcategory WHERE sub_cat_url like 'a%'
) a
order by url

答案 1 :(得分:0)

您可以尝试加入子类别表(未经测试):

SELECT cat.cat_url as cat_url, subcat.sub_cat_url as sub_cat_url FROM category as cat
left join subcategory as subcat on subcat.sub_cat_url like 'a%'
WHERE cat.cat_url like 'a%' 
ORDER BY cat.cat_url, subcat.sub_cat_url