[英]How to combine two SQL queries in one query
我有两个彼此不相关的查询,第一个查询返回4列,第二个查询仅返回1列。
那么如何结合呢?
查询1-
$sql = "select postlist.* from postlist order by postlist.id desc ";
查询2-
$sql1 = "select count (commentlist.id) as 'comments',commentlist.id,commentlist.name,commentlist.comment from postlist,commentlist where postlist.id=commentlist.post_id";
当前查询
$sql = "select postlist.*, count (commentlist.id) as 'comments' from postlist LEFT JOIN commentlist ON postlist.id=commentlist.post_id order by postlist.id desc ";
基本上,我想从postlist返回所有记录,无论commentlist表是否有任何相关注释。
这是一个数据库设计
drop table if exists postlist;
create table postlist (
id integer not null primary key autoincrement,
post varchar(1000) not null,
name varchar(80) not null,
title varchar(80) not null
);
drop table if exists commentlist;
create table commentlist (
id integer not null primary key autoincrement,
post_id integer not null,
comment varchar(80) not null,
name varchar(80) not null
);
get()会将其强制转换为一个Collection,它比数组强大得多。 您可以附加它,对其进行迭代等等。 对此有个打击。 希望它应该是您所需要的: http : //laravel.com/docs/4.2/eloquent#collections
$items = DB::select($sql)->get();
$items1 = DB::select($sql1)->get();
$items = items->toArray();
$items1 = items1->toArray();
$items = array_merge($items, $items1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.