1

So I have Laravel 5.2 and in my SQL database I have several tables: books with fields title, author and year, journals with fields title, year and price newspapers with fields title, town, year

I need to get a list of all titles from all three tables, where the year is 1994. I've tried to do the following

$titles = DB::table('books')->where('books.year', 1994)->leftjoin('journals as journals', 'books.year', '=', 'journals.year')->leftjoin('newspapers as newspapers', 'books.year', '=', 'newspapers.year')->select('books.title', 'journals.title', 'newspapers.title')->get();

But with this query I get entries full of nulls, and only newspapers are filled in. What am I doing wrong?

0

2 Answers 2

3

In this case (if the tables are not related) you should use union, no join.

$books = DB::table('books')->select('title')->where('year', 1994);
$journals = DB::table('journals')->select('title')->where('year', 1994);
$titles = DB::table('newspapers')->select('title')->where('year', 1994)->union($books)->union($journals)->get();
Sign up to request clarification or add additional context in comments.

Comments

1

You need to specify year column :

$titles = DB::table('books')
           ->where('books.year', 1994)
           ->leftjoin('journals as journals', 'books.year', '=', 'journals.year')
           ->leftjoin('newspapers as newspapers', 'books.year', '=', 'newspapers.year')
            ->select('books.title', 'journals.title', 'newspapers.title')
            ->get();

1 Comment

oh, I have it specified, I just lost it writing a post. sorry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.