2

I have a SQL query with a left join which works fine:

SELECT book.* FROM book
LEFT JOIN purchase ON book.book_id = purchase.book_id
WHERE purchase.user_id = 3
ORDER BY purchase.purchase_date

But I need also infos from purchase table, so I tried:

SELECT purchase.*, book.*
FROM purchase, book
LEFT JOIN purchase ON book.book_id = purchase.book_id
WHERE purchase.user_id = 3
ORDER BY purchase.purchase_date

But it does not work, I have this error message: #1066 - Not unique table/alias: 'purchase'

How can I do modify the first request to get data from purchase table also ?

Raidri
  • 17,258
  • 9
  • 62
  • 65
defacto
  • 359
  • 1
  • 5
  • 18

2 Answers2

3

Your 1st statement was nearly exactly what you want, you just need to name in the SELECT, which fields you want to return from purchase table.

e.g.

SELECT book.*, purchase.user_id 
FROM book 
    LEFT JOIN purchase ON book.book_id = purchase.book_id 
WHERE purchase.user_id = 3 
ORDER BY purchase.purchase_date

You don't need to list "purchase" in the FROM clause as well as in the JOIN - because you have, that is why you are seeing the error.

AdaTheDev
  • 142,592
  • 28
  • 206
  • 200
3

You do not need to refer to the purchase table in the FROM clause - that would mean that you are both cross-joining book and purchase tables and then joining purchase table again. Because there are two instances of purchase table, they need to have unique alias - thus the error. You probably just need this:

SELECT purchase.*, book.*  
  FROM purchase LEFT JOIN purchase ON book.book_id = purchase.book_id 
 WHERE purchase.user_id = 3 ORDER BY purchase.purchase_date;
onedaywhen
  • 55,269
  • 12
  • 100
  • 138
Aurimas
  • 2,518
  • 18
  • 23