0

我有以下 sql 查询:

//Get id
SELECT id from magazine where name = 'Web Designer'


SELECT avatar from person where newsletter = 1 and id in
(
 SELECT person_id as id FROM person_magazine WHERE magazine_id = 9 //use id from previous query
)

如何将它们组合起来,这样我就不必运行两个查询?

4

4 回答 4

4

我认为您需要了解联接。以下是您真正想要的查询:

SELECT p.avatar
from person p join
     person_magazine pm
     on pm.person_id = p.id join
     magazine m
     on pm.magazine_id = m.id
where p.newsletter = 1 and m.name = 'Web Designer'
于 2013-09-03T16:12:56.353 回答
0

嵌套查询:

SELECT avatar 
from person 
where 
    newsletter = 1 
    and id in (
        SELECT person_id as id 
        FROM person_magazine 
        WHERE magazine_id = (SELECT id from magazine where name = 'Web Designer' limit 1)
    )

或者使用一个变量:

set @mag_id = (SELECT id from magazine where name = 'Web Designer' limit 1);
SELECT avatar from person where newsletter = 1 and id in
(
    SELECT person_id as id FROM person_magazine WHERE magazine_id = @mag_id
)

limit 1用来确保只返回一行。

如果有更多行,请考虑使用join.

于 2013-09-03T16:14:32.133 回答
0

假设 person_magazine 表中只有一个人和杂志名称的条目。

SELECT avatar 
  FROM person P
 INNER JOIN  person_magazine PM
    ON P.id = pm.person_id
 INNER JOIN magazine M
    ON PM.magazine_id = M.id
 WHERE P.newsletter = 1
   AND PM.name = 'Web Designer'
于 2013-09-03T16:14:44.710 回答
0
SELECT avatar FROM person p
       INNER JOIN  person_magazine p_m ON p.id = p_m.person_id
       WHERE p.newsletter = 1
       AND p_m.name = 'Web Designer'
于 2013-09-03T16:16:30.407 回答