从两个表中基于相同的id进行SELECT并分组

时间:2015-04-01 09:23:36

标签: mysql sql

我有两个具有不同结构的表(table1已确认的项目,table2项目等待确认,每个用户可能在这两个表中有更多项目):

table1
id (primary) | user_id | group_id | name | description | active_from | active_to

table2
id (primary) | user_id | group_id | name | description | active_from

我尝试拥有的是某个用户的所有项目的列表 - 即两个表格中具有相同user_id(例如1)的行准备按group_id分组显示(即第一组1,然后组2等)由name排序(在每组内)。输出应该如下:

(all the groups below belong to the same user - with certain user_id)

# Group 1 (group_id) #
Item 67 (id): Apple (name), healthy fruit (description) (item stored in table1)
Item 29: Pear, rounded fruit (item stored in table2)

# Group 2 #
Item 14: Grape, juicy fruit (item stored in table2)

# Group 3 #
Item 116: Blackberry, shining fruit (item stored in table2)
Item 14: Plum, blue fruit (item stored in table1)
Item 7: Raspberry, red fruit (item stored in table1)

我无法找到可行的解决方案,我尝试使用JOIN以及使用SELECT子句的两个表中的简单WHERE

我结束了以下代码,这显然不起作用,因为返回错误(更高 - 冗余)的结果数量(不讨论table2的结果的未实现排序):

SELECT table1.id, table1.user_id, table1.group_id, table1.active_from, table1.active_to, table2.id, table2.user_id, table2.group_id, table2.active_from
FROM table1
LEFT JOIN table2
ON table1.user_id = table2.user_id
WHERE (table1.group_id='".$group_id."' OR table2.group_id='".$group_id."') AND (table1.user_id='".$user_id."' OR table2.user_id='".$user_id."')
ORDER BY table1.property_name ASC

3 个答案:

答案 0 :(得分:2)

union适合您的问题。需要进行一些数据按摩,以使联合的两侧具有相同数量和类型的列:

select  group_id
,       id as item_id
,       name
,       description
,       source_table
from    (
        select  id
        ,       user_id
        ,       group_id
        ,       name
        ,       description
        ,       'from table1' source_table
        from    table1
        union all
        select  id
        ,       user_id
        ,       group_id
        ,       name
        ,       description
        ,       'from table2'  -- Column name is already defined above
        from    table2
        ) as SubQueriesMustBeNamed
where   user_id = 1
order by
        group_id
,       name

Working example at SQL Fiddle.

要根据需要格式化结果集,请迭代结果集。当group_id更改时,请打印# Group N #标题。

客户端不应该有其他循环或迭代,只需要一个foreach或等同于查询返回的行集。

答案 1 :(得分:1)

select * from a t1 , b t2 where t1.user_id=t2.user_id and t1.group_id='' ORDER BY t1.name ASC 

答案 2 :(得分:0)

好的,根据您在评论部分的内容,我收集到两张表格无关。所以我们不想加入它们。

您希望获得两个数据集的并集结果(即两个表,或更准确地说:两个表的用户记录)。所以使用UNION,或者更好:UNION ALL,(正如Andomar已经建议的那样)。

您不需要任何GROUP BY,因为SQL中的GROUP BY意味着聚合数据(即每组获得一个结果行)。您想要通过group_id进行ORDER BY:

select *
from
(
  select group_id, id, name, description, 'confirmed' as status 
  from table1 where user_id = 12345
  union all
  select group_id, id, name, description, 'unconfirmed' as status
  from table2 where user_id = 12345
)
order by group_id;