2

我有 3 个表要加入,需要一些帮助才能使其工作,这是我的架构:

捐款:

+--------------------+------------+   
|   uid   |  amount  |   date     |
+---------+----------+------------+
|    1    |    20    | 2013-10-10 | 
|    2    |    5     | 2013-10-03 | 
|    2    |    50    | 2013-09-25 |
|    2    |    5     | 2013-10-01 |
+---------+----------+------------+

用户:

+----+------------+
| id |  username  | 
+----+------------+
| 1  |    rob     |
| 2  |    mike    | 
+----+------------+

原因:

+--------------------+------------+
|   id    |   uid    |   cause    | <missing cid (cause id)
+---------+----------+------------+
|    1    |    1     |  stop war  | 
|    2    |    2     |   love     | 
|    3    |    2     |   hate     | 
|    4    |    2     |   love     | 
+---------+----------+------------+

我想要的结果(为阅读目的而裁剪的数据)

+---------+-------------+---------+-------------+
|    id   |   username  | amount  |    cause    | 
+---------+-------------+---------+-------------+
|    1    |     rob     |   20    |  stop war   |
|    2    |     mike    |   5     |    love     |
+---------+-------------+-----------------------+

ETC...

这是我当前的查询,但返回双数据:

SELECT i.*, t.cause as tag_name
FROM users i
INNER JOIN donations tti ON (tti.uid = i.id)
INNER JOIN causes t ON (t.uid = tti.uid)

编辑:修复了小提琴 http://sqlfiddle.com/#!2/0e06c/1架构和数据上的 sql 架构

我怎么能做到这一点?

4

3 回答 3

1

看来您的桌子型号不对。原因和捐赠之间应该有关系。

如果不是在您进行连接时,您将获得重复的行。

例如。您的模型可能如下所示:

捐款

+--------------------+------------+
|   uid   |  amount  |   date     |  causeId
+---------+----------+------------+
|    1    |    20    | 2013-10-10 |     1
|    2    |    5     | 2013-10-03 |     2
|    2    |    50    | 2013-09-25 |     3
|    2    |    5     | 2013-10-01 |     2
+---------+----------+------------+

原因:

+----------------------+
|   id    |   cause    |
+---------+------------+
|    1    |   stop war | 
|    2    |   love     | 
|    3    |   hate     | 
+---------+------------+

那么正确的查询应该是这个

SELECT i.*, t.cause as tag_name
FROM users i
INNER JOIN donations tti ON (tti.uid = i.id)
INNER JOIN causes t ON (t.id = tti.causeId)
于 2013-10-27T19:34:45.867 回答
0

尝试这个

SELECT CONCAT(i.username ,' ',i.first_name) `name`, 
SUM(tti.amount), 
t.cause AS tag_name
FROM users i
LEFT JOIN donations tti ON (tti.uid = i.id)
INNER JOIN causes t ON (t.uid = tti.uid)
GROUP BY i.id

小提琴

于 2013-10-27T19:31:25.047 回答
0

您需要同时匹配用户表和原因表中的 id,如下所示:

SELECT i.*, t.cause as tag_name
FROM users i
INNER JOIN donations tti ON (tti.uid = i.id)
INNER JOIN causes t ON (t.uid = tti.uid and t.id = i.id)

抱歉格式化,我在手机上输入这个。

于 2013-10-27T19:33:13.980 回答