我正在使用此函数列出表helps
中的项目,具体取决于参数:(我包含了大部分代码但你真的只关注mysql查询)
function list_helps($by,$value,$page = -1,$ipp = 20){
/* Yes I concatenate querys... so i use some variables to help it a bit */
$sql = 'SELECT helps.* FROM helps ';
$where = ''; $orderBy = ''; $in = ''; $join = ''; $limit = ''; $resultitems = ''; $header = '';
if($page > 0) $limit = 'LIMIT '.$page*$ipp.', '.($page+1)*$ipp; else $limit = 'LIMIT 10';
switch($by){
case 'byuser':
$where = 'WHERE id_user ='.$value;
$orderBy = 'ORDER BY id DESC';
break;
case 'byfriend':
$sql = 'SELECT
h.*,
f.*
FROM (
SELECT
id,
CASE followerid WHEN '.$value.' THEN followingid ELSE followerid END AS friend_id
FROM friends
WHERE acepted = 1
AND (followerid = '.$value.' OR followingid = '.$value.')
) AS f
INNER JOIN helps AS h ON h.id_user = f.friend_id
ORDER BY h.id DESC';
break;
default:
break;
}
$sql .= $where.' '.$orderBy.' '.$limit;
$res = cache_query($sql,'',60*60*5);
/* checks in cache first, if not; executes query.. next code it's to render content */
}
还有更多案例,但我们可以关注这两个案例。
他们都服务于被请求的“帮助”(如果是用户,或者如果是用户的朋友);问题是当我试图检索那些评论时(如果它是博客文章);我正在这样做:
res = cache_query('SELECT help_replies.content, help_replies.date,
help_replies.offers, help_replies.accepted, help_replies.id_responds,
usuarios.first_name, usuarios.last_name, usuarios.avatar,usuarios.id
FROM help_replies left join usuarios
ON help_replies.id_user = usuarios.id
WHERE help_replies.id_responds = '.$this->id.'
ORDER BY help_replies.id ASC', '', 30);
foreach($res as $obj) {
/* $obj['id_responds'] */
}
}
问题是help_replies.id_responds
引用了该项,所以当'byuser'是好的时候;但是当案件是'byfriend'时,这个字段会丢失(所以总是会显示相同的评论)
结论:
任何想法为什么$ this-> id与(JOINED)查询不符合预期?
- 编辑 -
$ this-> id来自此构造方法(我省略了许多属性)
function __construct($item) {
$this->id = $item['id'];
$this->id_user = $item['id_user'];
..
}
$ item是foreach的一次迭代(因此返回的行转换为数组)
Muchas Gracias
答案 0 :(得分:4)
byfriends
执行的function list_helps(...)
查询似乎返回标记为id
两次的字段;一次用于helps
表,然后再次用于f
friends
表的别名,作为子查询的一部分。
我可以想象,如果$this->id
包含朋友ID 而不是帮助ID ,那么您的评论查询(help_replies
)将返回错误的结果。
所以也许更改子查询时会显示朋友ID的别名,如id AS friendsId,
一切都会按预期工作?
function list_helps($by,$value,$page = -1,$ipp = 20){
...
...
case 'byfriend':
$sql = 'SELECT
h.*,
f.*
FROM (
SELECT
id AS friendsId,
CASE followerid WHEN '.$value.' THEN followingid ELSE followerid END AS friend_id
FROM friends
WHERE acepted = 1
AND (followerid = '.$value.' OR followingid = '.$value.')
) AS f
INNER JOIN helps AS h ON h.id_user = f.friend_id
ORDER BY h.id DESC';
break;
由于这个原因,我养成了命名我的表标识符字段<tablename>Id
的习惯,并节省了在任何地方使用别名的费用。