需要一个MySQL查询来显示有孩子的父母和没有孩子的父母

时间:2019-02-14 02:32:47

标签: mysql sql

我有一个MySQL查询,该查询当前从三列表中获取所有类别及其子类别。表格中的每一行都包含一个catid,一个类别和一个parentid(如果没有parent,则为零)。

SELECT t1.category AS lev1, 
   t2.category as lev2, 
   t3.category as lev3, 
   t4.category as lev4
FROM categories AS t1
LEFT OUTER JOIN categories AS t2 ON t2.parentid = t1.catid
LEFT OUTER JOIN categories AS t3 ON t3.parentid = t2.catid
LEFT OUTER JOIN categories AS t4 ON t4.parentid = t3.catid
WHERE t1.parentid = 0  AND t1.cat_type = 'content'
ORDER BY lev1, lev2, lev3, lev4

它将返回我如下的数据集合:

sample cat 1 | sample cat 4 
sample cat 1 | sample cat 5 
sample cat 1 | sample cat 6 
sample cat 2 | sample cat 7 
sample cat 2 | sample cat 8 
sample cat 3 | sample cat 9  |  sample cat 11
sample cat 3 | sample cat 10 |  sample cat 12

问题是我需要显示主要的父类别,就好像它们没有子一样。因此,返回的数据应类似于“

sample cat 1 |               |
sample cat 1 | sample cat 5  |
sample cat 1 | sample cat 6  |
sample cat 2 |               |
sample cat 2 | sample cat 7  |
sample cat 2 | sample cat 8  |
sample cat 3 |               |
sample cat 3 | sample cat 9  |
sample cat 3 | sample cat 9  |  sample cat 11
sample cat 3 | sample cat 10 |
sample cat 3 | sample cat 10 |  sample cat 12

我修改了查询以自己获取顶级“亲猫”,但显然这不是正确的方法。

    SELECT category AS lev1,    catid   AS lev1catid,
       '' as lev2,  '' as lev2catid,
       '' as lev3,  '' as lev3catid FROM categories WHERE parentid = 0  AND cat_type = 'content' UNION ALL

SELECT t1.category AS lev1,     t1.catid AS lev1catid, 
       t2.category as lev2,     t2.catid as lev2catid,
          t3.category as lev3,  t3.catid as lev3catid
    FROM cat
    egories AS t1
    LEFT OUTER JOIN categories AS t2 ON t2.parentid = t1.catid
    LEFT OUTER JOIN categories AS t3 ON t3.parentid = t2.catid
    WHERE t1.parentid = 0  AND t1.cat_type = 'content'
    ORDER BY lev1, lev2, lev3

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

一种方法是Sub AutoUpdateCards() TickerCards.Activate Range("A1:ZZ1000").Clear tLog.Activate Dim tickers() As String Dim tSize As Integer, i As Integer, j As Integer Dim rngB As Range Set rngB = Range("$B2:$B1000") tSize = WorksheetFunction.SumProduct(1 / WorksheetFunction.CountIf(rngB, rngB)) ReDim tickers(tSize) 'store all unique tickers For i = 1 To tSize If i = 1 Then 'store initial ticker tickers(i) = Range("B" & i) Else 'compare with all of the currently stored tickers to make sure we aren't storing a duplicate For j = 1 To i Next j Next i End Sub

union all