连接两个表,主键是许多外键

时间:2017-11-12 22:24:25

标签: sql sql-server

我在SQL中有两个表,我想进行一个查询,我可以从第一个表中获取所有列,并从第二个表中获取相关颜色(基于id)。

结果应该连接第二个表中的颜色,以便每一行都有一个唯一的主键(我知道你不能有多个主键值)

enter image description here

我尝试过内连接,但这导致重复的主键。 (见下文)

我也尝试了一个联盟,但是我收到一个错误,说联盟需要有相同数量的列。

SELECT [Table1].[ID], [Table1].[Name], [Table1].[Job], [Table2].[Colour]
FROM 
[Table1]
INNER JOIN
[Table2] ON [Table1].[Id]  = [Table2].[Id]

2 个答案:

答案 0 :(得分:1)

这应该做的工作:

<?php
mb_internal_encoding("UTF-8");
include('/includes/db-connect.php');

$T_Repons['acceptCod'] = "bad";

if (isSet($_POST['certcode'])) {
    $sql = "SELECT * FROM `certificate_acheived_tbl` ";
    $sql .= "WHERE `cert_check_code` = ".$_POST['certcode'].")";

    $result = mysqli_query($con, $sql);

    $T_Repons['acceptCod'] = (mysql_num_rows($result) == 1) ? "ok" : "bad";
}
header('Content-type: application/json');
echo json_encode($T_Repons);
exit(0);
?>

结果:

CREATE TABLE T1 (
    ID INT,
    Name VARCHAR (25),
    Job VARCHAR (25)
    );
CREATE TABLE T2 (
    ID INT,
    Color VARCHAR (25)
    );

INSERT INTO T1 VALUES
(1, 'John', 'Worker'),
(2, 'Jane', 'Worker');

INSERT INTO T2 VALUES
(1, 'Blue'),
(1, 'Yellow'),
(1, 'Green'),
(2, 'Orange');

SELECT  *,
        ( 
            SELECT  T2.color + ' '
            FROM    T2  INNER JOIN 
                    T1 ON T2.ID = T1.ID
            WHERE TT.ID = T2.ID
            FOR XML PATH('')
        ) AS Colors
FROM    T1 TT

<强> Demo

答案 1 :(得分:0)

试试这个:

;with T1 as (
SELECT Id,  
Colour=STUFF  
(  
     (  
       SELECT ', ' + CAST(Colour AS VARCHAR(MAX))  
       FROM Table2 t2   
       WHERE t2.Id = t1.Id
       FOR XML PATH('')  
     ),1,1,''  
)  
FROM Table1 t1  
GROUP BY Id
)

Select A.Id,Name,Job,Colour 
from Table1 A,T1 B
where A.Id = B.Id

以下是我运行此查询的结果:

Id  Name    Job      Colour
---------------------------------------
1   Jane    Worker   Black, Yellow, Red
2   John    Worker   Purple, Blue, White
3   Kim     Worker   Grey, Green
4   Corit   Worker   Brown, Pink
5   Tata    Worker   Orange, Black