MySQL - 在另一个查询中使用来自一个查询的结果

时间:2014-05-10 13:12:09

标签: mysql sql database

我有这个查询,它给我带有两列的行,每列包含一个id。

SELECT idEng, idDutch
FROM phraseConnections
WHERE cat = '3'

id来自其他表,它们与我想要的短语相关联。

我试过这样的事情。

SELECT a.phrase, b.phrase
FROM phraseEnglish as a, phraseDutch as b
WHERE a.id = (SELECT idEng
FROM phraseConnections
WHERE cat = '3')
and b.id = (SELECT idDutch
FROM phraseConnections
WHERE cat = '3')

感谢。

3 个答案:

答案 0 :(得分:3)

更好地使用加入:

SELECT
   a.phrase,
   b.phrase
FROM
   phraseConnections pc
INNER JOIN
   phraseEnglish AS a
ON
   pc.idEng = a.id
INNER JOIN
   phraseDutch AS b
ON
   pc.idDutch = b.id
WHERE
   pc.cat = 3;

如果您想要一种(或两种)语言中没有相应行的记录,那么您可以使用外连接。

答案 1 :(得分:0)

错误必须是因为内部查询返回多个值。

尝试使用IN

SELECT a.phrase, b.phrase
FROM phraseEnglish as a, phraseDutch as b
WHERE a.id IN (SELECT idEng
           FROM phraseConnections
           WHERE cat = '3')
and b.id IN (SELECT idDutch
          FROM phraseConnections
          WHERE cat = '3')

答案 2 :(得分:-1)

您的问题可能是因为您不能要求单个值等于一组多个值。 要在SQL中更正此问题,请使用In

SELECT a.phrase, b.phrase
FROM phraseEnglish as a, phraseDutch as b
WHERE a.id In 
        (SELECT idEng
         FROM phraseConnections
         WHERE cat = '3')
    and b.id In
        (SELECT idDutch
         FROM phraseConnections
         WHERE cat = '3')

但是,此查询可以在没有子查询的情况下完成:

SELECT e.phrase, d.phrase
FROM phraseConnections c
   join  phraseEnglish e 
     on e.id = c.idEng
   join  phraseDutch d 
     on d.id = c.idDutch
Where e.Cat = '3'