2014-02-12 143 views
1

我有兩個表'all'和'jdetails'。我有一個現有的選擇查詢所有表上的作品。如果可用,我想從jdetails表中添加一些附加數據。mySQL select with PHP - left join

所有表:

judge, year, ... 

jane doe, 2012 

john doe, 2011 

jdetails表:

name, designation,... 

jane doe, level 1 

jane doe, level 5 

john doe, special 

如何更改我下面的查詢,以包括「指定的(從jdetails)每個法官(全部)?

我認爲左連接是解決方案,但我有where子句考慮。另外,我絕對必須在下面查詢這個查詢的結果,但是如果它存在的話,可以從jdetails表中添加數據。

此外,每個all.judge都可以有多行(jdetails.name)的指定,我想列爲單個值。例如jane doe將具有「1級5級」的指定值。

我將參加在all.judge = jdetails.name

當前查詢:

$rows = $my->get_row("SELECT all.judge, `year`, `totlevel_avg`, `totlevel_count`, `genrank`, `poprank`, `tlevel_avg`, `tlevel_count`, `1level_avg` as `onelevel_avg`, `1level_count` as `onelevel_count`, `2level_avg` as `twolevel_avg`, `2level_count` as `twolevel_count`, `3level_avg` as `threelevel_avg`, `3level_count` as `threelevel_count`, `4level_avg` as `fourlevel_avg`, `4level_count` as `fourlevel_count`, `PSGlevel_avg`, `PSGlevel_count`, `I1level_avg`, `I1level_count`, `I2level_avg`, `I2level_count`, `GPlevel_avg`, `GPlevel_count`, `states` from `all` where `id` ='{$term}'"); 

任何幫助是極大的讚賞。

回答

1

我沒有包括您在SELECT聲明中的所有內容,我只是用ams.*進行了總結。但是,以下鏈接all表到jdetails表,然後將指定分組到一個字段。然後我用在拉你在all表中需要的字段的其餘部分(SQL Fiddle)外查詢的結果:

SELECT ams.*, am.Desigs 
FROM 
(
    SELECT a.judge, GROUP_CONCAT(j.designation SEPARATOR ', ') AS Desigs 
    FROM `all` AS a 
    INNER JOIN jdetails AS j ON a.judge = j.name 
    GROUP BY a.judge 
) AS am 
INNER JOIN `all` AS ams ON am.judge = ams.judge 
+0

這工作,謝謝! – user2108863

0

下面是一個例子,可以幫助你:

`SELECT table1.column_name(s),table2.column_name(s) FROM table1 
LEFT OUTER JOIN table2 ON table1.column_name=table2.column_name 
AND table1.column_name='Parameter'` 

在哪裏表1是所有和表2是jdetails