【发布时间】:2015-04-01 09:23:35
【问题描述】:
我有两个结构不同的表(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 以及使用 WHERE 子句的两个表中的简单 SELECT。
我以下面的代码结束,由于返回了错误(高得多 - 冗余)的结果数量(不是谈论来自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
【问题讨论】:
-
请提供一些样本数据和预期结果。
-
你能用一些示例数据做一个 SQL 小提琴,这样我们就可以测试这个 + 预期的输出也会很好..
-
我同意其他人的观点:显示示例数据和预期输出。你说两张桌子都是关于物品的。那么物品的钥匙是什么?名字?还是group_id?表的自然键是什么(即除了技术 id 之外,表中还有什么是唯一的)? user_id + group_id?
-
上面添加的示例输出。致 Thorsten:table1 中项目的键是 id,table2 中是 id,如上所述(两个表都没有单个主键)。其他行也不能认为它们的组合是唯一的。
-
好的,我明白了。我已经添加了一个答案。乍一看,顺便说一下,数据库设计看起来并不好。 (例如:这似乎是一个用户 - 水果关系,但我们链接到的只有一个用户表,没有水果表。这可能是故意的,但看起来很可疑。)告诉我们,如果你需要这方面的帮助.