我有两个表,Category
和Member
:
Category: Member:
+--Id--+--Name--+ +--Id--+--Name--+--CategoryId--+
| 1 | Cat1 | | 1 | Mem1 | 2 |
| 2 | Cat2 | | 2 | Mem2 | 2 |
| 3 | Cat3 | | 3 | Mem3 | 1 |
+------+--------+ | 4 | Mem4 | 3 |
| 5 | Mem5 | 1 |
| 6 | Mem6 | 3 |
+------+--------+--------------+
我想要一个提供以下输出的查询:
Combined:
+--Name--+--IsCategory--+
| Cat1 | True |
| Mem3 | False |
| Mem5 | False |
| Cat2 | True |
| Mem1 | False |
| Mem2 | False |
| Cat3 | True |
| Mem4 | False |
| Mem6 | False |
+--------+--------------+
我知道如何使用JOIN在一行中输出其类别名称的每个成员,以及如何使用UNION在一个输出中列出所有类别和成员。我可以使用这两个命令的组合来实现所需的输出吗?或者我需要以某种方式执行FOR EACH循环?是否有可能获得我想要的东西?
编辑:
订单Cat1, Mem3, Mem5, Cat2, Mem1, Mem2,...
对我很重要。
答案 0 :(得分:1)
我试过这样可以检查一下
CREATE TABLE #Category
([Id] int, [Name] varchar(4))
INSERT INTO #Category
([Id], [Name])
VALUES
(1, 'Cat1'),
(2, 'Cat2'),
(3, 'Cat3')
CREATE TABLE #Member
([Id] int, [Name] varchar(4), [CategoryId] int)
;
INSERT INTO #Member
([Id], [Name], [CategoryId])
VALUES
(1, 'Mem1', 2),
(2, 'Mem2', 2),
(3, 'Mem3', 1),
(4, 'Mem4', 3),
(5, 'Mem5', 1),
(6, 'Mem6', 3)
SELECT NAME , CASE WHEN NAME LIKE'%CAT%' THEN 'TRUE' ELSE 'FALSE' END AS IS_CATEGORY FROM (SELECT * FROM #MEMBER UNION ALL
SELECT *,NULL AS COLUMN1 FROM #CATEGORY )A
输出
NAME IS_CATEGORY
Mem1 FALSE
Mem2 FALSE
Mem3 FALSE
Mem4 FALSE
Mem5 FALSE
Mem6 FALSE
Cat1 TRUE
Cat2 TRUE
Cat3 TRUE
答案 1 :(得分:1)
你可以使用union:
SELECT name, 0 as IsCategory
FROM member
UNION ALL
SELECT name, 1
FROM category
答案 2 :(得分:0)
根据@Chanukya和@Zohar Peled的答案,我找到了以下解决方案:
SELECT Name, IsCategory FROM
(SELECT Name as Name, 1 as IsCategory, id * 10000 as OrderNumber
FROM Category
UNION ALL
SELECT m.Name as Name, 0, c.id * 10000 + m.id as OrderNumber
FROM Members b JOIN Category c ON m.CategoryId = c.Id
) AS temp
ORDER BY OrderNumber;
这假设每个类别的成员不超过10000个,这对我当前的用例来说很好。但是,我感谢任何有关更优雅和正确方法的建议。