sqlmysqlmysql-error-1066

join on three tables? Error in phpMyAdmin


I'm trying to use a join on three tables query I found in another post (post #5 here). When I try to use this in the SQL tab of one of my tables in phpMyAdmin, it gives me an error:

#1066 - Not unique table/alias: 'm'

The exact query I'm trying to use is:

select r.*,m.SkuAbbr, v.VoucherNbr from arrc_RedeemActivity r, arrc_Merchant m, arrc_Voucher v
LEFT OUTER JOIN arrc_Merchant m ON (r.MerchantID = m.MerchantID)
LEFT OUTER JOIN arrc_Voucher v ON (r.VoucherID = v.VoucherID)

I'm not entirely certain it will do what I need it to do or that I'm using the right kind of join (my grasp of SQL is pretty limited at this point), but I was hoping to at least see what it produced.

(What I'm trying to do, if anyone cares to assist, is get all columns from arrc_RedeemActivity, plus SkuAbbr from arrc_Merchant where the merchant IDs match in those two tables, plus VoucherNbr from arrc_Voucher where VoucherIDs match in those two tables.)

Edited to add table samples

Table arrc_RedeemActivity
RedeemID | VoucherID | MerchantID | RedeemAmt
----------------------------------------------
1        | 2         |  3         | 25
2        | 6         |  5         | 50

Table arrc_Merchant
MerchantID | SkuAbbr
---------------------
3         | abc         
5         | def         

Table arrc_Voucher
VoucherID | VoucherNbr
-----------------------
2         | 12345       
6         | 23456

So ideally, what I'd like to get back would be:

RedeemID | VoucherID | MerchantID | RedeemAmt | SkuAbbr | VoucherNbr
-----------------------------------------------------------------------
1        | 2         | 3          | 25        | abc     | 12345
2        | 2         | 5          | 50        | def     | 23456

Solution

  • The problem was you had duplicate table references - which would work, except for that this included table aliasing.

    If you want to only see rows where there are supporting records in both tables, use:

    SELECT r.*,
           m.SkuAbbr, 
           v.VoucherNbr 
      FROM arrc_RedeemActivity r
      JOIN arrc_Merchant m ON m.merchantid = r.merchantid
      JOIN arrc_Voucher v ON v.voucherid = r.voucherid
    

    This will show NULL for the m and v references that don't have a match based on the JOIN criteria:

       SELECT r.*,
              m.SkuAbbr, 
              v.VoucherNbr 
         FROM arrc_RedeemActivity r
    LEFT JOIN arrc_Merchant m ON m.merchantid = r.merchantid
    LEFT JOIN arrc_Voucher v ON v.voucherid = r.voucherid