SQL Join和Jointure中的整数条件使它们相对

时间:2012-11-21 08:18:18

标签: sql join where

我已经提交了我的问题,但是没有例子它不够清楚,所以这里是表格:

Users
id_user / key_user
1       / 123FDADA21312QD
2       / 994GFCS4595433D

Companies
id_company / key_company
1          / 3123123123
2          / 5435345454

Products
id_product / id_company_product / code_product
1          /     1              / iphone
2          /     1              / iBook
3          /     1              / macbook

Tyds
id_tyd  / user_tyd / product_tyd
1       /   1      /   1        -- mean that the id_user = 1 made a line for the iphone 
                                   sold by the company 1
2       /   1      /   2        -- same : user 1 for the ibook of company 1

这是我的要求:

SELECT 
products.id_product,
users.id_user,
COALESCE(id_tyd, 'NONE') AS id_tyd 
FROM tyds
INNER JOIN users
ON tyds.user_tyd = users.id_user
INNER JOIN products
ON tyds.product_tyd = products.id_product
INNER JOIN companies
ON products.id_company_product = companies.id_company 
WHERE users.key_user = '123FDADA21312QD'
AND companies.module_key_company = '3123123123'
AND products.cancelled_product >= 0
AND products.code_product = 'iphone'

那将返回

products.id_product = 1
users.id_user = 1 
tyds.id_tyd = 1

完美。但我想做的是获取users.id_user即使在tyds中没有此用户的记录。喜欢:

SELECT 
products.id_product,
users.id_user,
COALESCE(id_tyd, 'NONE') AS id_tyd 
FROM tyds
INNER JOIN users
ON tyds.user_tyd = users.id_user
INNER JOIN products
ON tyds.product_tyd = products.id_product
INNER JOIN companies
ON products.id_company_product = companies.id_company 
WHERE users.key_user = '123FDADA21312QD'
AND companies.module_key_company = '3123123123'
AND products.cancelled_product >= 0
AND products.code_product = 'macbook'

我想得到:

  • products.id_product = 3
  • users.id_user = 1
  • tyds.id_tyd = NONE

因为在这一步,我确定我要求的产品存在且user_key存在。但我不确定tyds中是否有匹配的记录,这就是我想测试的内容。

当然,所有表格都是简化的,我需要更多的数据,但我认为这将是我的观点。

我的第一步是将WHERE条件放在JOIN匹配中,但是,不知道为什么,如果我将products.code_product放在产品的关节中,即使对于不同的id_product,它也会给我tyds记录...

非常感谢你的帮助!

1 个答案:

答案 0 :(得分:3)

如果是这种情况,请将联接从INNER JOIN更改为LEFT JOININNER JOIN,基本上返回所有正在连接的表上存在的行(至少一个匹配),而LEFT JOIN甚至返回左手方面的行没有匹配其他表上的记录。

查询,

SELECT c.*, d.id_tyd
FROM
    (
      SELECT  a.id_user, b.id_product
      FROM    users a CROSS JOIN products b
    ) c
    LEFT JOIN tyds d
      ON d.user_tyd = c.id_user AND
         d.product_tyd = c.id_product
    LEFT JOIN products e
      ON e.id_product = c.id_product
    LEFT JOIN companies f
      ON e.id_company_product = f.id_company
    LEFT JOIN users g
      ON c.id_user = g.id_user
WHERE e.code_product = 'macbook' AND
      f.key_company = '3123123123' AND
      g.key_user = '123FDADA21312QD'