MySQL结果集问题

时间:2015-01-30 11:49:08

标签: mysql symfony doctrine-orm

我有一系列作者姓名,我必须选择一些作者文章,但作者名称在文本内容中是有限制的。是否有任何好的解决方案,我不必一个一个地获取记录,我可以在一个查询中获得每个作者的记录。

SELECT n0_.id AS id0 
  FROM newspaper n0_ 
       INNER JOIN newspaper_translation n1_ ON n0_.id = n1_.translatable_id
       INNER JOIN newspaper_channels n3_ ON n0_.id = n3_.news_id 
       INNER JOIN channels c2_ ON c2_.id = n3_.channel_id 
 WHERE n1_.locale = 'zh_CN' 
   AND (c2_.reference_id = '057PL' AND n1_.content LIKE '%黎子珍%') 
 ORDER BY n0_.id DESC 
 LIMIT 1 

我希望传递多个作者姓名并希望获得每个作者的单个记录。但我想执行一次查询。

1 个答案:

答案 0 :(得分:0)

您可以使用where语句序列构建or子句:

WHERE n1_.locale = 'zh_CN' AND c2_.reference_id = '057PL' AND
      (n1_.content LIKE '%黎子珍%' OR n1_.content LIKE '%子珍%' OR n1_.content LIKE '%黎子%')

但是,如果您对数据库有任何控制权,则应该有一个与每个项目的作者匹配的表,每个作者和作者所处的项目都有一行。这被称为联结表,它使得回答这些类型的问题变得更加容易。

编辑:

您可以使用原始查询并使用union all重复该搜索:

(SELECT n0_.id AS id0 
  FROM newspaper n0_ 
       INNER JOIN newspaper_translation n1_ ON n0_.id = n1_.translatable_id
       INNER JOIN newspaper_channels n3_ ON n0_.id = n3_.news_id 
       INNER JOIN channels c2_ ON c2_.id = n3_.channel_id 
 WHERE n1_.locale = 'zh_CN' 
   AND (c2_.reference_id = '057PL' AND n1_.content LIKE '%黎子珍%') 
 ORDER BY n0_.id DESC 
 LIMIT 1 )
UNION ALL
(SELECT n0_.id AS id0 
  FROM newspaper n0_ 
       INNER JOIN newspaper_translation n1_ ON n0_.id = n1_.translatable_id
       INNER JOIN newspaper_channels n3_ ON n0_.id = n3_.news_id 
       INNER JOIN channels c2_ ON c2_.id = n3_.channel_id 
 WHERE n1_.locale = 'zh_CN' 
   AND (c2_.reference_id = '057PL' AND n1_.content LIKE '%黎珍%') 
 ORDER BY n0_.id DESC 
 LIMIT 1 )

但是,此时,您可能只是运行单独的查询。