如何从没有重复行的三个表中获取记录?

时间:2018-09-20 06:38:33

标签: php mysql

如何从三个没有重复行的表中获取记录?(已编辑的问题)  下面是我的表结构

--
-- table structure for table `users`
--
CREATE TABLE `users`(
`user_id` int(11)NOT NULL,
`name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(300) NOT NULL,
`time_joined` time NOT NULL,
`date_joined` date NOT NULL
)ENGINE=MyISAM  DEFAULT CHARSET=latin1;
--
-- table structure for table `activity`
--
CREATE TABLE `activity`(
`activity_id` int(11)NOT NULL,
`user_id` int(11) NOT NULL,
`time_loged` time NOT NULL,
`time_out` time NOT NULL
)ENGINE=MyISAM  DEFAULT CHARSET=latin1;
--
-- table structure for table `timeout`
--
CREATE TABLE `timeout`(
`timeout_id` int(11)NOT NULL,
`user_id` int(11)NOT NULL,
`time_out` time NOT NULL
)ENGINE=MyISAM  DEFAULT CHARSET=latin1;

这是我的努力

$id=$_SESSION['user'];
        $query = $conn->query("SELECT *  FROM users left join timeout on users.user_id=timeout.user_id left join activity on users.user_id=activity.user_id WHERE users.user_id='$id'");
    while($row = $query->fetch(PDO::FETCH_ASSOC))
    {

1 个答案:

答案 0 :(得分:0)

在'activity'和'timeout'上向左第二个联接,因此查询应如下所示:

SELECT * FROM users
LEFT JOIN timeout ON users.user_id = timeout.user_id
LEFT JOIN activity ON timeout.user_id = activity.user_id
WHERE users.user_id = '$id'

您可以在此处获得进一步的解释:https://www.codeproject.com/Questions/693539/left-join-in-multiple-tables