0

我有两张桌子,即 States & Districts 。这些表中的公共列是 StateID。

我想在该州的那个地区名称下显示州名

结果格式应如下所示:

泰米尔纳德邦

钦奈

哥印拜陀

卡纳塔克邦

班加罗尔

迈索尔。

.

.

请告诉我如何使用 sql 查询加入表以获取上述结果。

4

3 回答 3

2

请试试:

select StateID, StateName, 0 Sort from States
union all
select StateID, DistrictName, 1 Sort From Districts
order by StateID, Sort
于 2013-05-20T05:24:49.707 回答
1

这应该有效:

SELECT sc.name 
FROM
       states AS s2 
LEFT JOIN
       (SELECT s.statename AS name, 
               s.stateid 
          FROM   states s 
       UNION ALL 
       SELECT c.cityname AS name, 
              c.stateid 
          FROM   city c) AS sc 
ON sc.stateid = s2.stateid 

输出:

泰米尔纳德邦
钦奈
哥印拜陀
卡纳塔克邦
班加罗尔
迈索尔

于 2013-05-20T05:49:29.030 回答
0

SELECT StateName, group_concat(DistrictName)
  FROM Districts d JOIN States s
    ON d.StateID = s.StateID
group by StateName
ORDER BY StateName, DistrictName

于 2013-05-20T05:25:35.203 回答