简体   繁体   中英

how to combine two mysql queries to show their results in one dropdown

I have two table category and subcategory.In category table, i have one column cat_url.In subcategory table, i have one column sub_cat_url

What I want is to fetch all the URL of category table and subcategory table sorted alphabetically and show in menu dropdown

What i am doing is :

$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

} 

Try below query:

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

you can try to join the subcategory table like this (untested):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM