如何用PHP操纵这个SQL?

时间:2015-02-21 04:29:26

标签: php mysql

$lastquery = $db->query("
(SELECT l.pid as firstpost, l.islike as islike, t.username as username, l.thumbsup, t.subject as subject, l.dateline as dateline 
FROM ".TABLE_PREFIX."thumbspostrating l
LEFT JOIN   ".TABLE_PREFIX."threads t ON (t.firstpost = l.pid)
WHERE thumbsup)
UNION
(SELECT   t.firstpost, ' ' as islike, t.username as username, ' ' as nomames, t.views as views, t.dateline as dateline
FROM ".TABLE_PREFIX."threads t)
ORDER BY dateline DESC  
LIMIT ".(($page-1)*$perpage).", ".$perpage);


while ($post = $db->fetch_array($lastquery)) {

if ($post['islike'] == 1) { 
$template .= 'This is a like '.$post['firstpost'].'<br><br>';  
}    
else {
$template .= 'This is a post '.$post['firstpost'].' and '.$post['views'].'<br><br>';
}

}

echo $template;

我只是想分开帖子

的帖子

类似的东西:

$post['views'] <-- from second UNION,

$post['pid'] <-- from the first table 

我知道我可以做这种事情&#34; l.pid作为第一部分&#34;并通过相同类型的数据对此进行排序。

我这样做:

if ($post['islike'] == 1) { 
$template .= 'This is a  like '.$post['firstpost'].'<br><br>';  
}    
else {
$template .= 'This is a post '.$post['firstpost'].' and '.$post['views'].'<br><br>';
}

我错过了哪些东西?

2 个答案:

答案 0 :(得分:0)

$lastquery = $db->query(" 
SELECT  l.dateline as dateline, l.islike, u.username as username 
FROM ".TABLE_PREFIX."thumbspostrating l
LEFT JOIN   ".TABLE_PREFIX."threads t ON (t.firstpost = l.pid)
LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid = l.uid)
UNION
SELECT t.dateline as dateline, ' ', u.username as username
FROM ".TABLE_PREFIX."threads t
LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid = t.uid)
ORDER BY dateline DESC  
LIMIT ".(($page-1)*$perpage).", ".$perpage);


while ($post = $db->fetch_array($lastquery)) {

if ($post['islike'] == 1) { 
$template .= 'Esto es un like '.$post['dateline'].' user '.$post['username'].'<br><br>';  
}    
else {
$template .= 'Esto es un post '.$post['dateline'].' ademas '.$post['username'].'<br><br>';
}

}

分辨

答案 1 :(得分:0)

您需要在第二个请求中选择与第一个相同的列。如果您需要其他值,则需要在第一个请求中添加这些列。简而言之 - 用另一个条件复制第一个请求。剂量不符合您的别名如何命名第二个请求的值将由第一个请求别名和相同的顺序提供。