mySQL选择PHP - 左连接

时间:2014-02-12 20:26:56

标签: php mysql join subquery

我有两张桌子'all'和'jdetails'。我在所有表上都有一个现有的select查询。我想在jdetails表中添加一些额外的数据(如果有的话)。

所有表格:

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}'");

非常感谢任何帮助。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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