编辑:让我重新开始,因为我无法删除我的帖子
我有三张桌子
messages
messages_share
users
我有两个问题
query(1)从表消息中获取数据
SELECT
`messages`.*, `users`.`uid`, `users`.`username`, `users`.`full_name`, `users`.`profile`
FROM
`messages`
LEFT JOIN
`users` ON `messages`.`owner_id`=`users`.`uid`
WHERE
`messages`.`to_id` IN ($ids)
ORDER BY
`messages`.`time` DESC
LIMIT
$start, $min
query(2)从messages_share
获取数据SELECT
`messages`.*, `messages_share`.*, `users`.`uid`, `users`.`username`, `users`.`full_name`, `users`.`profile`
FROM
`messages_share`
LEFT JOIN
`users` ON `messages_share`.`share_owner_id`=`users`.`uid`
LEFT JOIN
`messages` ON `messages`.`share_message_id`=`messages`.`id`
WHERE
`messages_share`.`share_to_id` IN ($ids)
ORDER BY
`messages_share`.`time` DESC
LIMIT
$start, $min
我需要将这些查询组合在一起,以便根据它从哪个表中获取,LEFT JOIN用户从正确的表中拉出,并且ORDER BY按消息和messages_share进行排序
sudo查询应该如下所示
SELECT
if(table_we_are_pulling_from=`messages_share`)
`messages_share`.*,
`messages`.*, `users`.`uid`, `users`.`username`, `users`.`full_name`, `users`.`profile`
FROM
`messages_share`,
`messages`
if(table_we_are_pulling_from=`messages_share`)
LEFT JOIN `users` ON `messages_share`.`share_owner_id`=`users`.`uid`
else if(table_we_are_pulling_from=`messages`)
LEFT JOIN `users` ON `messages`.`owner_id`=`users`.`uid`
WHERE
if(table_we_are_pulling_from=`messages_share`)
`messages_share`.`share_to_id` IN ($ids)
else if(table_we_are_pulling_from=`messages`)
`messages`.`to_id` IN ($ids)
ORDER BY
`messages`.`time` DESC
`messages_share`.`share_time` DESC
LIMIT
$start, $min
答案 0 :(得分:0)
如果您使用的是PHP,则可以简单地动态构建此查询。
$table_we_are_pulling_from = '`messages_share`'; //or `messages`
$other_table = '`messages`';
$table_id = '`share_owner_id`'; // or '`owner_id`'
$to_id = '`share_to_id`'; // or '`to_id`';
$message_time = '`share_time`';
$query = " SELECT $table_we_are_pulling_from.*, `users`.`uid`, `users`.`username`, `users`.`full_name`, `users`.`profile`
FROM
$table_we_are_pulling_from
LEFT JOIN `users` ON $table_we_are_pulling_from.$table_id = `users`.`uid`
WHERE
$table_we_are_pulling_from.$to_id IN ($ids)
ORDER BY
$table_we_are_pulling_from.$messages_time DESC
LIMIT
$start, $min
如果您正在进行OOP,另一个选项是构建一个接口,使用两个对象实现它,并根据您在其他地方设置的条件,将选择将返回正确查询的对象。例如,
interface Messages { public function getUsersQuery(); }
class NormalMessages implements Messages {
public function getUsersQuery() { //return query for regular messages }
}
class SharedMessages implements Messages {
public function getUsersQuery() { //return query for shared messages }
}
然后,在你的代码中......
if (//some condition) $messages = new SharedMessages();
$query = $messages->getUsersQuery();