使用子选择从多个表中拉回行?

时间:2009-07-29 18:10:09

标签: sql database postgresql select

我有一个脚本,它以下列方式生成查询(基于用户输入):

SELECT * FROM articles 
 WHERE (articles.skeywords_auto ilike '%pm2%') 
  AND spubid IN (
   SELECT people.spubid FROM people 
   WHERE (people.slast ilike 'chow') 
   GROUP BY people.spubid) 
 LIMIT 1;

结果数据集:

Array ( [0] => 
  Array ( 
          [spubid] => A00603 
          [bactive] => t 
          [bbatch_import] => t 
          [bincomplete] => t 
          [scitation_vis] => I,X 
          [dentered] => 2009-07-24 17:07:27.241975 
          [sentered_by] => pubs_batchadd.php 
          [drev] => 2009-07-24 17:07:27.241975 
          [srev_by] => pubs_batchadd.php 
          [bpeer_reviewed] => t 
          [sarticle] => Errata: PM2.5 and PM10 concentrations from the Qalabotjha low-smoke fuels macro-scale experiment in South Africa (vol 69, pg 1, 2001) 
          [spublication] => Environmental Monitoring and Assessment 
          [ipublisher] => 
          [svolume] => 71 
          [sissue] => 
          [spage_start] => 207 
          [spage_end] => 210 
          [bon_cover] => f 
          [scover_location] => 
          [scover_vis] => I,X 
          [sabstract] => 
          [sabstract_vis] => I,X 
          [sarticle_url] => 
          [sdoi] => 
          [sfile_location] => 
          [sfile_name] => 
          [sfile_vis] => I
          [sscience_codes] => 
          [skeywords_manual] => 
          [skeywords_auto] => 1,5,69,2001,africa,assessment,concentrations,environmental,errata,experiment,fuels,low-smoke,macro-scale,monitoring,pg,pm10,pm2,qalabotjha,south,vol 
          [saward_number] => 
          [snotes] => 

问题是我还需要'people'表中的所有列(在子选择中引用)作为数据集的一部分返回。我(显然)过去没有做过子选择,所以这种方法对我来说很新。如何从articles表中将所有匹配的行/列拉回作为people表中的行/列?

3 个答案:

答案 0 :(得分:1)

你熟悉加入吗?使用ANSI语法:

SELECT DISTINCT *
  FROM ARTICLES t
  JOIN PEOPLE p ON p.spubid = t.spudid AND p.slast ILIKE 'chow'
 WHERE t.skeywords_auto ILIKE'%pm2%'
 LIMIT 1;

DISTINCT不必为从两个表返回的每个列定义GROUP BY。我把它包括在内,因为你的子查询中有GROUP BY;我不知道这是否真的有必要。

答案 1 :(得分:0)

在这种情况下你能否使用连接而不是子选择?

SELECT a.*, p.*
FROM articles as a
INNER JOIN people as p ON a.spubid = p.spubid
WHERE a.skeywords_auto ilike '%pm2%'
AND p.slast ilike 'chow'
LIMIT 1;

答案 2 :(得分:0)

让我们从头开始

  • 你不应该需要一个小组。改为使用distinct(你没有在内部查询中进行任何聚合)。
  • 要查看内部表的内容,您实际上必须加入它。除非显示在from部分中,否则内容不会公开。从people表到articles表的左外连接应该等同于IN查询:

    SELECT *
    FROM people 
    LEFT OUTER JOIN articles ON articles.spubid = people.spubid 
    WHERE people.slast ilike 'chow' 
    AND articles.skeywords_auto ilike '%pm2%' 
    LIMIT 1