两个表的SQL AND / OR条件

时间:2011-01-10 05:17:58

标签: sql mysql ruby-on-rails join

假设我们在MySQL数据库的后续数据结构和数据中有类Person,Character和PersonCharacter及其相应的结构。

table persons
[
  { id: 1, name: peter },
  { id: 2, name: mary },
  { id: 3, name: joe },
  { id: 4, name: paul },
  { id: 5, name: may },
]

table characters
[
  { id: 101, description: cheerful },
  { id: 102, description: nervous },
  { id: 103, description: greedy },
  { id: 104, description: sincere },
  { id: 105, description: naive },
  { id: 106, description: firm },
]

table person_characters
[
  {id: 1000, person_id: 1, character_id: 101},
  {id: 1001, person_id: 1, character_id: 103},
  {id: 1002, person_id: 1, character_id: 106},
  {id: 1003, person_id: 2, character_id: 102},
  {id: 1004, person_id: 2, character_id: 104},
  {id: 1005, person_id: 3, character_id: 102},
  {id: 1006, person_id: 3, character_id: 105},
  {id: 1007, person_id: 4, character_id: 104},
  {id: 1008, person_id: 5, character_id: 101},
  {id: 1009, person_id: 5, character_id: 106},
]

如果可能的话,我如何在Rails的帮助下编写一个SQL语句,可以找到具有特定字符的人?例如,具有坚定和快乐性格的人可以和彼此。

问题似乎很典型,但搜索引擎很难找到答案。

2 个答案:

答案 0 :(得分:0)

SELECT  persons.*
FROM    persons
  JOIN  person_characters
  ON    person_characters.person_id ON persons.id
    AND
      -- vvv Method one, we already have the character IDs: vvv
      person_characters.character_id IN (101,106)
      -- ^^^ /Method one ^^^

      -- vvv Method two, we need to look them up vvv
      person_characters.character_id IN (
        SELECT characters.id
        FROM   characters
        WHERE  characters.description IN ('cheerful','firm')
      )
      -- ^^^ /Method two ^^^

注意在连接中的AND之后仅使用其中一个语句。我只是展示了这两种方法(如果您有或没有要查找的字符的ID。

答案 1 :(得分:0)

  

有特殊的人   字符?

每个查询一个字符特征或多个(例如“同时'紧张'和'坚定'的人”)?

如果是多个,请将参数('紧张'和'坚定')放在表格中,然后使用relational division