正确查询加入两个查询

时间:2016-10-29 15:45:03

标签: php mysql join

我有这个查询选择列表

$sql="select *  from buy_log where (client_id  not in 
                (select selected_client_id from action_log where media_id=buy_log.media_id and client_id=$client_id ) 
                    and totalVisit>0 and coin_id=3 or coin_id=4 or coin_id=5)"; 

这是我的第二个选择

        while($row=mysqli_fetch_assoc($result)){
            $media_id = $row['media_id'];
            $sql2 = "select * from comment_media,comment_list where comment_list.id=comment_media.id and media_id='$media_id' order by rand() limit 2";
            }

我尝试使用join进行一次查询,这是我的尝试:

SELECT S.*,WW.Comments,WW.Comments_id
FROM buy_log S

INNER JOIN 
(
    SELECT M.media_id,GROUP_CONCAT(W.Comment SEPARATOR '!###!') as Comments,GROUP_CONCAT(W.id SEPARATOR ',') as Comments_id
    FROM comment_list W,comment_media as M
    Where W.id=M.id and M.media_id='$media_id' and W.used = 0

) WW
        ON S.media_id = WW.media_id
            where (client_id  not in 
                (select selected_client_id from action_log where media_id=S.media_id and client_id='1234' ) 
                    and totalVisit>0 and coin_id=3 or coin_id=4 or coin_id=5)

但这是我的问题

Where W.id=M.id and M.media_id='$media_id' and W.used = 0

我不知道如何设置$media_id

任何解决方案?

更新 表信息: Tables Info : Pic

2 个答案:

答案 0 :(得分:0)

这应该有效:

您从原始查询中提取媒体ID,循环结果并使用媒体ID在php循环中分配值$ media_id,您可以在其中执行另一个查询。

连接似乎在语法上正确,只需要引用子查询中的buy_log表。

SELECT S.*,WW.Comments,WW.Comments_id
FROM buy_log S

INNER JOIN 
(
    SELECT M.media_id,GROUP_CONCAT(W.Comment SEPARATOR '!###!') as Comments,GROUP_CONCAT(W.id SEPARATOR ',') as Comments_id
    FROM comment_list W,comment_media as M
    Where W.id=M.id and M.media_id= S.media_id and W.used = 0

) WW
        ON S.media_id = WW.media_id
            where (client_id  not in 
                (select selected_client_id from action_log where media_id=S.media_id and client_id='1234' ) 
                    and totalVisit>0 and coin_id=3 or coin_id=4 or coin_id=5)

答案 1 :(得分:0)

我猜第一个查询可以重写如下......这有帮助吗?

SELECT b.media_id  
  FROM buy_log b
  LEFT 
  JOIN action_log a
    ON a.selected_client_id = b.client_id
   AND a.media_id = b.media_id 
   AND a.client_id = $client_id 
 WHERE b.totalVisit > 0 
   AND b.coin_id IN(3,4,5)
   AND a.selected_client_id IS NULL;