【问题标题】:Mysql Query Join two table Order by one table columnMysql查询连接两个表按一个表列排序
【发布时间】:2026-02-12 04:50:01
【问题描述】:

我有两个表(表 1 和表 2)。我想通过加入 table2 来显示 table1 中的所有行,table2 有多个具有相同 table1 id(外键关系)的行,并将按 table2 优先级列对结果进行排序(按 desc 排序)。

表1

表2

结果将是

提前致谢

编辑

Table1

id   name

1   test1 
2   test2
3   test5
4   test7
5   test9
6   test3


Table2


id  table1_id   event   priority

1   2             abc      0
2   2             kbc      0
3   2             abc      2
4   2             kbc      1
5   4             fgg      2
6   4             dss      3
7   1             fgfg     2
8   5             fgfg     2
9   6             xcxc     1
10  6             fgfh     3

Result

id_table1   name    event   priority

4   test7   dss     3
6   test3   fgfh    3
2   test2   abc     2
1   test1   fgfg    2
5   test9   fgfg    2
3   test5   NULL    NULL

【问题讨论】:

  • 是我自己还是没有输入图片?你不能直接在架构下吗?
  • 对不起。您无法查看图片?
  • 是的,但这可能只是因为我们的防火墙。您不能输入架构吗?
  • @TheProvost 我已经更新了问题。

标签: php mysql sql join


【解决方案1】:

在您提到的问题中,您需要选择 table1 中的 id 在 table2 中不止一次可用的数据,这与您提供的结果集不匹配。

考虑到原始要求,以下应该可以解决问题

select
t2.table1_id as id_table1,
t1.name,
t2.priority,
t2.event
from table1 t1
join
(
  select 
  p1.table1_id,
  p1.event,
  p2.priority
  from table2 p1
  join(
    select
    max(priority) as priority,
    table1_id
    from table2
    group by table1_id having count(*) > 1
  )p2
  on p2.table1_id = p1.table1_id and p2.priority = p1.priority

)t2
on t1.id = t2.t1id
order by t2.priority desc

这是demo

结果将得到相同的event 对应于max priority

【讨论】:

  • 是的。您的查询是正确的,但我想显示 table1 的所有结果。如果 table2 上的外键不可用,该行将显示为 NULL,我也不想要 ((with count(*) > 1)) .. 谢谢..
  • 在这种情况下,您可以执行 from table1 t1 left join ( ... ) 并删除 having 子句。
  • 很酷的例子是sqlfiddle.com/#!2/38344/4,如果你想显示id和名字,你需要选择t1.table1_id as id_table1而不是t2.table1_id as id_table1
  • 有什么办法可以优化查询吗?如果我只需要 table1 的名称?
  • 是的,您可以在外部查询中选择您想要的任何内容,但请确保内部查询选择正确的数据,因为它用于连接和分组。
【解决方案2】:

这将得到你想要的结果集。您提到您只需要反映不止一次的项目 table1 id,但结果查询显示 tableid1 "1",即使它只出现一次:

SELECT DISTINCT t1.id,t1.name ,t2.event, t2.priority
FROM TABLE2 t2
right join 
TABLE1 t1
on t1.id=t2.table1_id
order by t2.priority desc

【讨论】:

  • 抱歉,您的查询与我的预期结果集不匹配。它在结果集上显示重复名称。请检查我的结果集。按优先级排序,您的查询没问题,但只会显示 6 行。需要在查询中添加 group by 子句...
【解决方案3】:

试试这个查询:

SELECT t1.*,t2.priority FROM table1 t1
INNER JOIN table2 t2
ON t1.id=t2.id
ORDER BY t2.priority DESC

【讨论】:

  • 如您所见,要求显示表 2 中不存在的值。所以使用内部连接并不是真正的答案。
【解决方案4】:

主键和外键应该同名。语法应该是

SELECT Table1.id_table1,Table1.name,Table2.event,Table.priority FROM
Table1 LEFT JOIN Table2 ON
Table1.id=Table2.id
ORDER BY Table2.priority DESC

在表 2 中进行以下更改:

  1. 删除第一列或重命名它
  2. 将第二列(您的外键)重命名为“id”。

【讨论】:

  • 如您所见,要求显示表 2 中不存在的值。所以使用内部连接并不是真正的答案。