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

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”表中的所有列(如子选择中引用的)作为数据集的一部分返回。我过去(显然)没有对子选择做太多事情,所以这种方法对我来说是非常新的。如何从文章表中提取所有匹配的行/列以及从人员表中提取行/列?

有帮助吗?

解决方案

你熟悉加入吗?使用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;我不知道这是否真的有必要。

其他提示

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

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;

让我们从头开始

  • 你不应该需要分组依据。使用不同的代替(您没有在内部查询中进行任何聚合)。
  • 要查看内表的内容,您实际上必须连接它。除非出现在 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
    
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top