views:

29

answers:

2

I'm trying to do a pretty complex query in MySQL; complex for me, at least.

Here's an example of what I'm trying to do:

SELECT * FROM friends
LEFT JOIN users ON users.uid = friends.fid1
LEFT JOIN users ON users.uid = friends.fid2
WHERE (friends.fid1 = 1) AND (friends.fid2 > 1)
UNION SELECT fid2 FROM friends
WHERE (friends.fid2  = 1) AND (friends.fid1 < 1)
ORDER BY RAND()
LIMIT 6;

I'm getting back: ERROR 1066 (42000): Not unique table/alias: 'users'.

Where am I going wrong, and how should I really be performing this query?

+3  A: 

Alias your table, like:

LEFT JOIN users u1 ON u1.uid = friends.fid1
LEFT JOIN users u2 ON u2.uid = friends.fid2
konforce
That solved one problem. Now I'm getting back `ERROR 1222 (21000): The used SELECT statements have a different number of columns`. Any thoughts?
Josh Smith
+1: Always make aliases (table and column) unique
OMG Ponies
@Josh Smith: With respect, that's a different error so ask a new question.
OMG Ponies
Respect noted and suggestion taken! Also, I should note for any other readers that I've read that aliasing should really be done as ...`users AS u1`... for better readability. I'm not sure if there's any benefit besides that, but that's a big enough benefit for me to warrant doing so.
Josh Smith
For those interested, I posted my follow-up question here: http://stackoverflow.com/questions/3655708/the-used-select-statements-have-a-different-number-of-columns-redux
Josh Smith
+1  A: 

You have written left join two times with different fields of tables, it seems to When it got parse so give them alias and then join them with friends Table

LEFT JOIN users users1 ON users1.uid = friends.fid1
LEFT JOIN users users2 ON users2.uid = friends.fid2
Azhar