简体   繁体   中英

How to combine two SQL queries in one query

I have two queries which are unrelated to each other, first query returns 4 column whereas the second one returns only 1 column.

so how to combine it?

query 1-

 $sql = "select postlist.* from postlist order by postlist.id desc ";

query 2-

 $sql1 = "select count (commentlist.id) as 'comments',commentlist.id,commentlist.name,commentlist.comment from postlist,commentlist where postlist.id=commentlist.post_id";

current query-

 $sql = "select postlist.*, count (commentlist.id) as 'comments' from postlist  LEFT   JOIN commentlist ON postlist.id=commentlist.post_id order by postlist.id desc ";

Basically, I want to return all records from postlist, whether the commentlist table has any related comments or not.

Here is a database design

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
); 

The get() will cast it to a Collection, that is a lot more powerful than an array. You can append it, iterate over it and more. Have a bash at that. Hopefully it should be what you need: 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM