简体   繁体   中英

Mysql join two tables based in id

I have two tables one is country another one state.Based on country id i need to group the state.I tried with joining but i couldn't get.How to get same table names in one columns and id also.

country example:

在此处输入图片说明

State example:

在此处输入图片说明

Expected Results

在此处输入图片说明

Thanks in advance.

You don't have to use join. Union with alias will work. Here's your query:

SELECT r.name, r.type, r.parent_id, r.og 
FROM (
    SELECT c.name AS name, 'country' AS type, 0 AS parent_id, c.origin AS og 
    FROM country c
    UNION
    SELECT s.name AS name, 'state' AS type, s.country_id AS parent_id, s.country_id  AS og 
    FROM STATE s  
) as r 
ORDER BY r.og, r.parent_id

Here, og is an extra projection created to match your sorting need.

select *
from country
join state
on state.country_id = country.origin

you can group by by just adding

group by country_id 

As far as mixing the results from two queries, just use UNION ALL between the two queries. Easy.

SELECT query 1.
UNION ALL
SELECT query 2.

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