简体   繁体   English

MySQL选择查询内部连接表,其中2个正则表达式针对不同的表

[英]MySQL select query inner joined tables with 2 regexp targeting different tables

Im using PHP MySQLi prepared statements for the querying 我使用PHP MySQLi编写的语句进行查询

$stmt = $dbconnect->prepare("

    SELECT COUNT(r.review_id)
         , p.postid
         , p.title
         , p.tags
         , p.ltags
         , p.status
         , p.timestamp 
      FROM njdb.post_review r
      JOIN njdb.post_si p
     WHERE r.postid REGEXP ? 
       AND r.review_status = 'a' 
       AND p.postid REGEXP ? 
       AND p.status = 'a';

   ");
$stmt->bind_param('ss',$search,$search);
$stmt->execute();
$stmt->bind_result($result_post_review, $result_postid, $result_title, $result_hashtags, $result_location, $result_status, $result_timestamp);

$search is a string with a value like id1|id2|id3|id4 $search是一个字符串,其值类似于id1|id2|id3|id4

There are 2 tables in play here post_si AND post_review 这里有2 tablespost_sipost_review

I am expecting the above to give me the total number of reviews + the details of the post. 我期待上面给出的评论总数+帖子的详细信息。 But I'm having problems in the WHERE area because some of the posts don't have any reviews so the AND post_review.review_status = 'a' is causing some of the problems. 但我在WHERE区域遇到问题,因为有些帖子没有任何评论,所以AND post_review.review_status = 'a'导致了一些问题。

I think what I really need is to use conditional statements but I haven't tried that in mysql if no reviews its ok just get the details of the post and move on to the next post How do I do that? 我认为我真正需要的是使用条件语句,但我没有在mysql中尝试过if no reviews its ok just get the details of the post and move on to the next post我该怎么做? Thanks! 谢谢!

You need to use a LEFT JOIN to get posts that have no matching reviews. 您需要使用LEFT JOIN来获取没有匹配评论的帖子。 You also need a proper join condition, to link posts with their reviews. 您还需要一个适当的加入条件,将帖子与他们的评论联系起来。 And a GROUP BY clause to get the counts by post, otherwise you total everything in one result. 还有一个GROUP BY子句通过post来获取计数,否则你将一切都归结为一个结果。

SELECT COUNT(r.review_id)
     , p.postid
     , p.title
     , p.tags
     , p.ltags
     , p.status
     , p.timestamp 
  FROM njdb.post_si p
  LEFT JOIN njdb.post_review r ON r.postid = p.postid AND r.review_status = 'a'
 WHERE p.postid REGEXP ? 
   AND p.status = 'a'
 GROUP BY p.postid;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM