1

我有 2 个要加入的表。

Table 1是一个主表,包含一组唯一的行。

ID DESCRIPTION
01 Alpha
02 Gamma
03 Delta
04 Beta

Table 2是一个包含许多行的明细表,其中只有一些行与主表匹配。

ID   INFO MASTER_ID
0001 abc  02
0002 def  02
0004 xyz  01
0005 mno  04

我想加入表格以产生以下结果:

Alpha "has detail"
Gamma "has detail"
Delta "does not have detail"
Beta "has detail"

而不是:

Alpha "has detail"
Gamma "has detail"
Gamma "has detail"
Delta "does not have detail"
Beta "has detail"

后面的输出返回 Gamma 两次,我只希望它返回一次。

我尝试了 LEFT JOIN、RIGHT JOIN、INNER JOIN,但它们都没有产生我想要的结果。

感谢您的帮助。

4

6 回答 6

3

使用LEFT JOIN可能你错过了一些东西

SELECT  CONCAT(a. description, IF(b.master_ID IS NOT NULL, ' has detail',' does not have detail'))
FROM    table1 a
        LEFT JOIN (SELECT DISTINCT master_ID FROM table2) b
            ON a.ID = b.master_ID
于 2012-10-31T15:57:30.100 回答
1

也许是这样的:

SELECT
    Table1.DESCRIPTION,
    (
        CASE 
            WHEN EXISTS(SELECT NULL FROM Table2 WHERE Table2.MASTER_ID=Table1.ID)
            THEN 'has detail'
            ELSE 'does not have detail'
        END
    ) AS has
FROM
    Table1
于 2012-10-31T15:57:18.087 回答
1

只是一种不同的方法:

SELECT
  table1.description,
  IF((EXISTS(SELECT master_id from table2  where table2.master_id = table1.id)),
    'has detail',
    'does not have detail') As Status
FROM table1
于 2012-10-31T16:21:58.667 回答
0
SELECT a.Description, IF(b.Info, "has detail", "does not have detail") as Status
FROM Table_1 a
LEFT OUTER JOIN Table_2 b
ON a.MASTER_ID = b.MASTER_ID
GROUP BY 1,2;
于 2012-10-31T16:07:33.420 回答
0

如果您的输出包含详细信息部分,那么您必须查看两行(因为它是有效结果),或者您需要通过选择 FIRST、MAX 等来聚合结果。

如果您本身不需要详细信息值,则替代方法是执行两个 SELECT 并使用 UNION:

    SELECT DISTINCT Table1.Description, "does not have detail" as Comment
    FROM Table1
    LEFT JOIN Table2 ON (Table1.ID = MASTER_ID)
    WHERE Table2.id IS NULL

    UNION 

    SELECT DISTINCT Table1.Description, "has detail" as Comment
    FROM Table1
    LEFT JOIN Table2 ON (Table1.ID = MASTER_ID)
    WHERE Table2.id IS NOT NULL
于 2012-10-31T16:10:25.350 回答
0

您也可以使用 groupby 来实现此目的

SELECT a.Description, IF(count(b.id) > 0, "has detail", "does not have detail") as Status
FROM Table1 a
LEFT OUTER JOIN Table2 b
ON a.iD = b.MASTER_ID
GROUP BY a.Description ORDER BY a.Description ASC
于 2012-10-31T16:14:26.090 回答