Select rows from a table where row in another table with same id has a particular value in another column

后端 未结 3 2060
有刺的猬
有刺的猬 2021-02-04 08:46

In MySQL:

If we have two tables:

comments
key    |    value
=================
1      |    foo
2      |    bar
3      |    foobar
4      |    barfoo


        
相关标签:
3条回答
  • 2021-02-04 09:24

    I actually wouldn't recommend a JOIN for this — or rather, I'd recommend a "semijoin", which is a relational-algebra concept not directly expressed in SQL. A semijoin is essentially a join where you want to retrieve records from only one table, but with the proviso that they have corresponding records in a different table.

    In SQL notation, this concept is expressed indirectly, by using an IN clause, with a subquery:

    SELECT key, value
      FROM comments
     WHERE key IN
            ( SELECT comment_key
                FROM meta
               WHERE value = 1
            )
    ;
    

    (MySQL will actually end up translating that back into a semijoin internally — essentially a sort of degenerate inner-join — but the IN clause is the natural way to express it in raw SQL.)

    0 讨论(0)
  • 2021-02-04 09:42

    I would use "INNER JOIN" in the following way:

    SELECT comments.key, comments.value FROM comments 
    INNER JOIN meta ON comments.key=meta.comment_key WHERE meta.value = 1;
    

    Cheers! ;-)

    0 讨论(0)
  • 2021-02-04 09:46

    You're looking for a plain, vanilla equi-join here.

    SELECT `comment`.`key`   AS `key`,
           `comment`.`value` AS `value`
        FROM `comments` 
            JOIN `meta` 
                ON `comments`.`key` = `meta`.`comment_key` 
        WHERE `meta`.`value` = 1;
    

    I'm not really sure what sort of advice you're looking for here but you can read more about the topic (not MySQL specific) at Wikipedia's SQL JOIN page.

    I'd recommend indexing on comment.key and meta.comment_key with both being PRIMARY KEY indexes assuming that you want there to only be 1 meta row per comment row (PRIMARY KEYs are UNIQUE by definition). If you want to allow more than 1 meta per comment then add a separate index id column to meta and make that the PRIMARY KEY with comment_key just a b-tree index.

    I'm also not sure how the performance of this will compare to the "semi-join" answer also listed but, to me, this is the simpler and more natural way to express the query; with only two tables, though, it shouldn't be too challenging for MySQL to optimize.

    0 讨论(0)
提交回复
热议问题