Frage

I have three tables called Hours, Projects and Clients. I'm somewhat experienced with SQL statements and can't seem to get my head around why this isn't working.

Projects and Hours tables both share a foreign key called projectid and Projects and Clients both share a foreign key called clientid.

Here's my query so far:

SELECT hoursworked.h, projectname.p, description.p, archive.p, clientname.c 
FROM hours AS h, projects AS p, clients AS c
JOIN h
ON projectid.h = projectid.p
JOIN p
ON clientid.p = clientid.c
WHERE archive.p = 0;

I seem to be getting an error called "#1066 - Not unique table/alias: 'h' "

Not sure where I am going wrong here. Any help would be great.

Thanks in advance!

War es hilfreich?

Lösung

You are mixing implicit joins and explicit joins. A simple rule: don't use commas in from clauses.

SELECT h.hoursworked, p.projectname, p.description, p.archive, c.clientname
FROM hours h join
     projects p
     on h.projectid = p.projectid join
     clients c
     ON p.clientid = c.clientid
WHERE p.archive = 0;

In addition, the syntax for using aliases is <table alias>.<column alias>, not the other way around.

Andere Tipps

You are using your aliases backwards. You need to use H.HoursWorked, rather than HoursWorked.H, etc. Your JOIN is also incorrect.

Try the following:

SELECT  h.hoursworked, p.projectname, p.description, p.archive, c.clientname 
FROM    hours AS h
JOIN    projects AS p ON h.projectid = p.projectid
JOIN    clients AS c ON p.clientid = c.clientid
WHERE   p.archive = 0;

You need to prepend the table name to the field/column, not put it at the end, and usually you would use AS for field/column aliases, not for table aliases. Also, I would name the tables in the JOINs, not separated by commas in the FROM statement. This is how it should look:

SELECT 
    h.hoursworked, 
    p.projectname, 
    p.description, 
    p.archive, 
    c.clientname 
FROM hours h
JOIN projects p
    ON h.projectid = p.projectid
JOIN clients c
    ON p.clientid = c.clientid
WHERE p.archive = 0;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top