如何选择条件为多行的信息?

时间:2016-11-30 08:27:53

标签: sql request

如何从User表中选择一些信息(例如NAMESURNAME),在Option表格中,我想要选择的用户具有选项20以及选项25的信息,例如?

在此示例中,我想选择用户NAME的{​​{1}}和SURNAME,因为它是唯一同时拥有选项120

25表格

Option

+---------+---------+ | ID_USER | OPTIONS | +---------+---------+ | 1 | 20 | +---------+---------+ | 1 | 25 | +---------+---------+ | 2 | 20 | +---------+---------+ | 3 | 25 | +---------+---------+ 表格

User

结果表

+---------+---------+----------+
| ID_USER | NAME    | SURNAME  |
+---------+---------+----------+
| 1       | Jean    | Baptiste |
+---------+---------+----------+
| 2       | Henry   | Charles  |
+---------+---------+----------+
| 3       | Jacques | François |
+---------+---------+----------+

3 个答案:

答案 0 :(得分:0)

我不确定我理解你的问题,但我认为以下选择会做:

SELECT NAME , SURENAME
  FROM User
 WHERE ID_User IN (SELECT ID_User 
                     FROM Option
                    WHERE OPTIONS IN (20,25)
                  )

答案 1 :(得分:0)

试试这个:

SELECT u.name,u.surname

FROM user u, option o

WHERE u.id_user=o.id_user

AND o.options IN (20,25)

答案 2 :(得分:0)

执行JOIN获取组合,使用WHERE过滤掉预期的选项。 GROUP BYHAVING COUNT DISTINCT相结合,以确保有20和25个值。

select u.NAME, u.SURNAME
from User u
join Option o on o.ID_USER = u.ID_USER
where o.options IN (20, 25)
group by u.NAME, u.SURNAME
having count(distinct o.options) = 2

注意: USER是ANSI SQL中的保留字,因此您可能需要将其分隔为"User"