【问题标题】:how to get orphans from a join table in MySQL如何从 MySQL 中的连接表中获取孤儿
【发布时间】:2013-10-15 00:41:15
【问题描述】:

假设有 2 个表,第一个是产品列表(产品),第二个是产品和另一个表(类别)之间的连接表,称为 products-categories

产品:

id   |  name
------------
1       Lorem 
2       Ipsum 
3       Dolor 
4       Sit 

产品类别

product_id  | categories_id
---------------------------
1             3
1             6
4             1
2             2

如何获取孤儿元素,我的意思是没有类别的元素,所以在这种情况下:3,使用 MyISAM 以一种有效的方式(+30k 记录)?

这有点像显示所有不可连接的行,但这种语法对我来说很奇怪......

【问题讨论】:

    标签: mysql sql myisam


    【解决方案1】:
    select * from products p 
    left join product_categories pc on p.id=pc.product_id 
    where pc.product_id is null
    

    将返回 product_Category 中未找到的表 products 中的所有产品。 LEft join 和 where 非常快。 30k 条记录也很少,所以不用担心。

    【讨论】:

      【解决方案2】:
      select p.id from products p left join product-categories c on p.id=c.product_id 
      where c.id is NULL
      

      【讨论】:

        【解决方案3】:

        一旦我使用了以下类似的东西,我遇到了类似的问题

        select p.id from products p left join productscategories pc where pc.categories_id is null

        -hj

        【讨论】:

          【解决方案4】:

          使用子查询:

          SELECT name FROM products 
          WHERE id NOT IN (SELECT product_id FROM products-categories);
          

          使用连接

          SELECT name FROM products 
          LEFT JOIN products_categories ON (id=product_id)
          WHERE product_id IS NULL;
          

          加入加入更好 sqlfiddle 演示:http://sqlfiddle.com/#!2/684c1/8

          【讨论】:

            猜你喜欢
            • 2011-10-20
            • 1970-01-01
            • 2014-10-06
            • 2014-10-07
            • 2020-09-30
            • 1970-01-01
            • 2018-03-22
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多