【问题标题】:MySQL syntax for CONCAT depending same table column?CONCAT的MySQL语法取决于相同的表列?
【发布时间】:2021-11-30 19:07:37
【问题描述】:

这是我的桌子:

pkey Name Report_to
11 abc 12
12 def 13
13 sdf 11
14 dfg

我想要这样的输出:

Name Report_to
abc def
def sdf
sdf abc
dfg

我已经试过了:

SELECT CONCAT( CASE WHEN `Report_TO` = `PKEY` THEN Name ELSE CONCAT( "no one " ) END )

现在我得到输出:

Name Report_to
abc no one
def no one
sdf no one
dfg no one

是否可以得到我想要的输出。

【问题讨论】:

  • MySQL SQL Server - 请更正您的标签。
  • 您使用的是 MySQL 还是 MS SQL Server?
  • 你想要一个 self (left) join,没有 concat。
  • 我正在使用 mysql @jarlh

标签: mysql concatenation string-concatenation


【解决方案1】:

您可以将同一张表的多个副本加入到自身,但是为了在查询中区分每个这样的副本(但最多一个)必须赋予其他一些唯一的,别名在查询中被知道。

因为您仍然希望在输出中包含dfg,即使他们没有向他们报告,您需要一个外部连接。外连接有左连接和右连接两种,表示即使连接谓词不匹配,连接记录仍应包含在哪一侧。

因此,您可以使用 (sqlfiddle):

SELECT     reporter.Name AS Reporter, reportee.Name AS Reportee
FROM       my_table AS reporter
LEFT JOIN  my_table AS reportee
        ON reportee.pkey = reporter.Report_to
ORDER BY   reporter.pkey

或 (sqlfiddle)

SELECT     reporter.Name AS Reporter, reportee.Name AS Reportee
FROM       my_table AS reportee
RIGHT JOIN my_table AS reporter
        ON reportee.pkey = reporter.Report_to
ORDER BY   reporter.pkey

Jeff Atwood(Stack Overflow 的共同创始人)写了一篇精彩的博文,您可能会感兴趣,A Visual Explanation of SQL Joins

【讨论】:

    【解决方案2】:

    只需将表连接到自身并使用左连接来选择所需的列:

        select tbl1.name , tbl2.name  from docs tbl1 
    left join  docs tbl2 on tbl1.report_to = tbl2.pkey
    

    注意:将 table_name 替换为您的表的实际名称:

    table_name --> your tables name

    sql 小提琴here

    【讨论】:

    • 没有tbl2,我只有一张桌子@aliFidanli
    • @eggyal 你是对的。我修好了
    • @sai 它的别名,而不是表名。你能试试吗?应该没问题
    • 此外,问题中显示的所需输出将需要反转所选列的顺序或连接谓词的逻辑。目前您显示的是reportee, reporter 而不是reporter, reportee
    猜你喜欢
    • 2013-11-28
    • 2015-03-14
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 2017-04-13
    • 1970-01-01
    相关资源
    最近更新 更多