简体   繁体   English

如何为此场景编写SQL查询?

[英]How to write SQL query for this Scenario?

An interviewer asked me this question, You are given two tables with columns as L1,T1 for table1 while T,Name for table2. 一位采访者问我这个问题,给你两个表,其中列为L1,T1为表1,T为表2的名称。 Write a SQL query to get the desired result. 编写SQL查询以获得所需的结果。 在此输入图像描述

I'm still stuck on how to write the query to get the desired output. 我仍然坚持如何编写查询以获得所需的输出。

Used this, SELECT table1.L1, table2.Name FROM table1 INNER JOIN table2 on table1.T1 = table2.T; 使用此表, SELECT table1.L1, table2.Name FROM table1 INNER JOIN table2 on table1.T1 = table2.T; but this way it won't CONCAT the output for Name wrt L1. 但这样它就不会为Name wrt L1输出CONCAT。

Thanks for helping in advance. 感谢您提前帮助。

You need an aggegation function as GROUP_CONCAT for obtain the comma separated result for name 您需要一个aggegation函数作为GROUP_CONCAT来获取name的逗号分隔结果

  SELECT table1.L1,GROUP_CONCAT( table2.Name ORDER BY table2.Name ASC SEPARATOR ',')
  FROM table1 
  INNER JOIN table2 on table1.T1 = table2.T
  GROUP BY table1.L1 
  ORDER BY FIELD(table1.L1,'X','Y','Z')

withou aggegation function you get result on separated rows .. instead with group by an group_concat you obtain all the name related to a one l1 on the same row withou aggegation函数你得到分隔行的结果..而不是group_concat的group你获得与同一行上的一个l1相关的所有名称

You join the two tables using JOIN (Inner Join). 您使用JOIN (内部联接)加入两个表。 Then use GROUP BY to get aggregated data, and then eventually utilize GROUP_CONCAT function to achieve comma separated names. 然后使用GROUP BY获取聚合数据,最后使用GROUP_CONCAT函数来实现逗号分隔的名称。 See below: 见下文:

SELECT table1.l1, GROUP_CONCAT(table2.name) 
FROM table1 
JOIN table2 ON table1.t1 = table2.t 
GROUP BY table1.l1

use this query 使用此查询

SELECT table1.L1, GROUP_CONCAT(table2.name separator ', ')
FROM table1 AS table1
INNER JOIN table2 as table2 ON table1.T1 = table2.t
GROUP BY table1.L1

SQL fiddle here to test it live http://sqlfiddle.com/#!9/3ac3a3/1/0 SQL小提琴在这里测试它http://sqlfiddle.com/#!9/3ac3a3/1/0

这个sql会得到结果。

SELECT L1, GROUP_CONCAT(name) from Table1 INNER JOIN Table2 on T1 = T GROUP BY L1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM