如何使用join从一行获取数据?

时间:2016-05-19 08:01:54

标签: mysql join

我有两张桌子,如下所示:

表1

  id     name      address   phone
   1     Nirdosh   Shrestha  984901
   2     krishna   hora      984902
   7     birami    pokhara   984903

表2

  id     weight   destination  age
   1     52       balkhu       32
   2     53       hanger       35
   2     65       fursad       35
   3     70       Ktm          10

我想要这样的结果表:

预期结果表

 id     name      address   phone  id  weight  destination  age
  1     Nirdosh   Shrestha  984901  1   52       balkhu       32
  2     krishna   hora      984902  2   53       hanger       35
  2     krishna   hora      984902  2   65       fursad       35

我试过和sql查询是:

select table1.*,table2.*
from table1 LEFT JOIN table2
ON table1.id = table2.id;

但是我的查询没有给出预期的结果。

2 个答案:

答案 0 :(得分:3)

嗯,'不工作'不是很清楚。根据您的样本,我猜您只想保留那些匹配的记录?

在这种情况下,它应该是INNER JOIN

select t1.*,t2.*
from table1 t1
JOIN table2 t2
 ON table1.id = table2.id;

答案 1 :(得分:0)

此解决方法可能会解决您的问题。首先将子查询作为公共ID并使用WHERE子句进行检查:

SELECT T1.*, T2.*
FROM Table1 T1
INNER JOIN Table2 T2 ON T2.ID = T1.ID
WHERE T1.ID IN  (
    SELECT DISTINCT T1.ID
    FROM Table1 TT1
    INNER JOIN Table2 TT2 ON TT2.ID = TT1.ID)

使用给定表执行示例。我尝试了 SSMS ,因此语法可能会有所不同。

DECLARE @Table1 TABLE (id int, name varchar(20), [address] varchar(20), phone int)

insert into @Table1 (id,name, [address] ,phone)
VALUES
   (1, 'Nirdosh', 'Shrestha',984901),
   (2, 'krishna', 'hora',984902),
   (7, 'birami', 'pokhara',984903)

DECLARE @Table2 TABLE (id int, [weight] int, [destination] varchar(20), age int)

insert into @Table2 (id, [weight], destination, age)
VALUES
   (1, 52, 'balkhu' ,32),
   (2, 53, 'hanger' ,35),
   (2, 65, 'fursad' ,35),
   (3, 70, 'Ktm ' ,10)

SELECT T1.*, T2.*
FROM @Table1 T1
INNER JOIN @Table2 T2 ON T2.ID = T1.ID
WHERE T1.ID IN  (
    SELECT DISTINCT T1.ID
    FROM @Table1 TT1
    INNER JOIN @Table2 TT2 ON TT2.ID = TT1.ID)