Mysql Query连接两个表按一个表列排序

时间:2014-11-07 07:17:40

标签: php mysql sql join

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

表1

enter image description here

表2

enter image description here

结果将是

enter image description here

提前致谢

修改

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

4 个答案:

答案 0 :(得分:3)

在您提到的问题中,您需要选择table1table2的ID多次出现的数据,该数据与您提供的结果集不匹配。

考虑到原始要求,以下应该做的伎俩

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相同

答案 1 :(得分:0)

这将获得您想要的结果集。您提到您只需要反映多次的item table 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

答案 2 :(得分:-1)

尝试此查询:

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

答案 3 :(得分:-1)

主键和外键应具有相同的名称。语法应为

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"。