2016-07-21 14 views
0

Ich habe die folgende Abfrage:MySQL COUNT ??? Hilfe für die Suche nach

select AP.paper_id as id, 
concat(A.organization, A.country)as org, 
group_concat(SUBSTR(first_name, 1, 1), '. ', last_name SEPARATOR ', ') as initial 
       from authors A 
           inner join authors__papers AP ON A.author_id = AP.author_id 
           join tmp_orgs ORGS ON ORGS.paper_id = AP.paper_id 
           where ORGS.organization=A.organization AND 
           AP.is_contact_author < 1 
           group by A.organization, AP.paper_id 
       order by AP.paper_id, idx 

Es gibt Daten simlar an:

id  org initial 
1001 org1 J. Doe 
1001 org1 J.Smith 
1003 org2 A. Doe 
1004 org3 A. Smith 
1004 org3 B. Doe 
1006 org4 B. Smith 
1007 org5 C. Doe 

Was ich brauche, ist eine vierte Spalte, die eine Zählung aller Orgs von paper_id so die gruppiert ist Ergebnisse würden wie folgt aussehen:

id  org initial org_count 
1001 org1 J. Doe 2 
1001 org1 J.Smith 2 
1003 org2 A. Doe 1 
1004 org3 A. Smith 2 
1004 org3 B. Doe 2 
1006 org4 B. Smith 1 
1007 org5 C. Doe 1 

ich müde, um eine Add-Unterabfrage:

(SELECT COUNT (DISTINCT (Organisation)) als DCnt von Autoren A INNER JOIN authors__papers AP auf AP.author_id = A.author_id wo AP.is_contact_author < 1 UND paper_id = ??? GROUP BY paper_id) als org_count

... aber kann nicht herausfinden, wie die paper_id für jede Zeile (die ??? in der Abfrage oben angeben. Und ist es besser, dies als eine Join oder Spalte in der ?.! zu wählen, oder ist es wirklich wichtig ich bin nicht wirklich ein SQL-Typ, aber haben es brauchen, weil ich bin für jemanden Ausfüllen Jede Hilfe ist willkommen

Antwort

1

Sie sind fast da, versuchen Sie dies:

SELECT 
    AP.paper_id AS id, 
    CONCAT(A.organization, A.country) AS org, 
    GROUP_CONCAT(SUBSTR(first_name, 1, 1), '. ', last_name SEPARATOR ', ') AS initial, 
    (
     SELECT COUNT(DISTINCT(organization)) AS dcnt 
     FROM authors t1 
     INNER JOIN authors__papers t2 ON t2.author_id = t1.author_id 
     -- INNER JOIN tmp_orgs t3 ON t3.paper_id = t2.paper_id AND t3.organization = t1.organization 
     WHERE t2.is_contact_author < 1 
    ) AS org_count 
FROM authors A 
INNER JOIN authors__papers AP ON A.author_id = AP.author_id 
INNER JOIN tmp_orgs ORGS ON ORGS.paper_id = AP.paper_id 
WHERE ORGS.organization = A.organization 
AND AP.is_contact_author < 1 
GROUP BY A.organization, AP.paper_id 
ORDER BY AP.paper_id, idx 
+0

tmp_orgs ist eine temporäre Tabelle und getting '# 1137 - Kann die Tabelle nicht wieder öffnen: 't3' –

+0

@DDurham Kommentiere die' JOIN' Zeile aus, überprüfe sie bitte noch einmal: – Blank

+0

Eigentlich konnte ich Ihr Beispiel verwenden, um die Join-Funktion stattdessen in der Abfrage für temporäre Tabellen einzufügen. Jetzt kann ich sie einfach in der Hauptabfrage auswählen. Vielen Dank! –