简体   繁体   English

我的SQL查询涉及多个表

[英]My SQL query involving multiple tables

I have 2 tables. 我有2张桌子。 First table stores id in multiple column whose value is stored in other table. 第一个表将id存储在多列中,其值存储在另一个表中。 I want a query that returns result which has structure of my 1st table but values from 2nd table. 我想要一个返回结果的查询,该结果具有我的第一张表的结构但来自第二张表的值。 To be more specific let's say I have a table like this: 更具体地说,假设我有一个这样的表:

Table A : 表A

        Uniqueid  song_1  song_2 song_3 song_4 song_5
           1        2       4     5        6      8

Table B : 表B

                  song_id    song_name
                     1         abcd
                     2         def
                     3         efg
                     4         ghi
                     5         abdal
                     6         nsadln
                     7         knwldn
                     8         jdkabdb

I want to fetch data from Table A but it should look like: 我想从表A中获取数据,但它看起来应该像这样:

Desired result: 所需结果:

        Uniqueid  song_1  song_2  song_3    song_4   song_5
           1       def      ghi   abdal      nsadln  jdkabdb

I have used join and making objects but no luck so far. 到目前为止,我已经使用过join和make对象,但是没有运气。 Please help me out. 请帮帮我。

Just use a bunch of left joins to get to your answer: 只需使用一堆左联接即可得到答案:

SELECT
    a.UniqueId
    ,s1.song_name as song_1
    ,s2.song_name as song_2
    ,s3.song_name as song_3
    ,s4.song_name as song_4
    ,s5.song_name as song_5
FROM
    TableA a
    LEFT JOIN TableB s1
    ON a.song_1 = s1.song_id 
    LEFT JOIN TableB s2
    ON a.song_2 = s2.song_id
    LEFT JOIN TableB s3
    ON a.song_3 = s3.song_id 
    LEFT JOIN TableB s4
    ON a.song_4 = s4.song_id
    LEFT JOIN TableB s5
    ON a.song_5 = s5.song_id

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

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