0

我想从三个具有多对多关系的表中获取数据。这是我的数据库的表结构。

用户

uid[pk] fname lname username
 1      John  smith johnsmith

活动

act_id[pk] title
 log       Account Login
 reg       Account Registration

用户活动

serial_number[pk] act_id[fk] user_id[fk] ip_address date time
1                  reg           1       2.2.2.2      - 
2                  log           1       1.1.1.1      -                

我正在尝试获取:

title  ip_address date time

这是我的mysqli查询语句:

SELECT a.title, ua.ip_address, ua.date, ua.time FROM users u 
LEFT JOIN user_activity ua ON ua.user_id = u.uid 
LEFT JOIN activity a ON a.activity_id = ua.act_id 
WHERE u.username=?"

它从数据库中获取数据,我得到 3 个结果,而不仅仅是 1 个:

Title            Ip_address      Date                Time

Account Login    1.1.1.1         Mon,Nov4 2013       5:5pm
Account Login    1.1.1.1         Mon,Nov4 2013       5:5pm
Account Login    1.1.1.1         Mon,Nov4 2013       5:5pm

我使用了 DISTICT,但它不起作用。如果我错了,请纠正我。谢谢

4

2 回答 2

0

I figured out it myself. Now its working fine. Here is the query.

SELECT a.title, ua.ip_address, ua.date, ua.time
FROM users AS u
LEFT JOIN user_activity AS ua ON ua.user_id = u.uid
LEFT JOIN activity AS a ON a.activity_id = ua.act_id
WHERE u.username = 'johnsmith'
GROUP BY ua.serial_number
于 2013-11-04T14:46:08.033 回答
0

如果我理解正确,您只需要添加一个GROUP BY

SELECT 
  title, ip_address
FROM
  users AS u
LEFT JOIN
  user_activity AS ua ON ua.user_id = u.uid
LEFT JOIN
  activity AS a ON a.activity_id = ua.act_id 
WHERE
  u.username = ?
GROUP BY
  ua.ip_address
于 2013-11-04T13:30:49.570 回答