使用WHERE从两个相同的表中选择数据

时间:2015-04-24 10:41:00

标签: mysql sql join

我有这个例子:

CREATE TABLE ForgeRock
    (`id` int, `productName` varchar(7), `description` varchar(55))
;

INSERT INTO ForgeRock (`id`, `productName`, `description`)
VALUES (1, 'OpenIDM', 'Platform for building enterprise provisioning solutions'),
       (2, 'OpenAM', 'Full-featured access management'),
       (3, 'OpenDJ', 'Robust LDAP server for Java');

CREATE TABLE ForgeRock2
    (`id` int, `productName` varchar(7), `description` varchar(55))
;

INSERT INTO ForgeRock2 (`id`, `productName`, `description`)
VALUES (1, 'OpenIDM', 'Platform for building enterprise provisioning solutions'),
       (2, 'OpenAM', 'Full-featured access management'),
       (3, 'OpenDJ', 'Robust LDAP server for Java');

为什么这个查询给了我三个条目?

SELECT
  ForgeRock.productName,
  ForgeRock.description
FROM
  ForgeRock, ForgeRock2
WHERE
  ForgeRock.id = 2;

输出:

productname | description
---------------------------------------------
OpenAM      | Full-featured access management
OpenAM      | Full-featured access management
OpenAM      | Full-featured access management

以下是示例

SQLFiddle

任何人都可以解释为什么结果包含3个条目吗?!

2 个答案:

答案 0 :(得分:2)

你正在做的交叉连接。因此,表1中id = 2的条目被映射到表2的每个条目,即3个条目,因此你得到3行 如果您仍想使用交叉连接 -

SELECT
  ForgeRock.productName,
  ForgeRock.description
FROM
  ForgeRock, ForgeRock2
 WHERE
 ForgeRock.id = 2 and forgeRock2.id = 2

更好的解决方案 -

SELECT
  a.productName,
  a.description
FROM
  ForgeRock a JOIN  ForgeRock2 b
  ON a.id = b.id
 WHERE
 a.id = 2 

答案 1 :(得分:2)

此查询

SELECT
  ForgeRock.productName,
  ForgeRock.description
FROM
  ForgeRock, ForgeRock2
 WHERE
 ForgeRock.id = 2;

这是CROSS JOIN,意味着show every data combination from ForgeRock and ForgeRock2。对于ForgeRock,您添加了条件ForgeRock.id = 2,因此结果是ForgeRock2与行ForgeRock.id = 2的每个组合。在表ForgeRock2中,您有3行,因此您在结果中看到3行。

要正确使用,您需要加入以下

   SELECT
      ForgeRock.productName,
      ForgeRock.description
    FROM ForgeRock
     join  ForgeRock2 on ForgeRock2.id = ForgeRock.id
     WHERE
     ForgeRock.id = 2;

或者您也可以使用旧标准(但我推荐以上标准)

 SELECT
      ForgeRock.productName,
      ForgeRock.description
    FROM
      ForgeRock, ForgeRock2
     WHERE
     ForgeRock.id = 2
     and ForgeRock2.id = ForgeRock.id;