我已经很长时间没有进行JOIN查询了,所以我很生锈。我所拥有的:一个称为触发器和用户的表。最初,我只是有一个查询,该查询从触发器表中选择了所有信息。这包括一个user_id。好吧,我认为不仅仅是将user_id显示为用户名,而是将其显示为用户名。
记录来自各种用户名,因此显示的用户名必须与触发器表中的user_id匹配到用户表的id。这是我迷路的地方。将t.user_id与u.id匹配后,我不知道该怎么办。如何获取这些记录的u.username?
我仍然希望显示所有记录,就像您执行SELECT * FROM触发器一样。我只想能够使用正确的用户名进行记录。
这是我尝试过的。我从这里开始出错:
SELECT (
u.username
):
任何帮助将不胜感激。数据库表如下所示。
$sql_triggers = "
SELECT
t.*,
u.id,
u.username
FROM
triggers AS t
LEFT JOIN
users AS u ON t.user_id = u.id
SELECT (
u.username
)
";
$triggers_stmt = $con->prepare($sql_triggers);
$triggers_stmt->execute();
$triggers_rows = $triggers_stmt->fetchAll(PDO::FETCH_ASSOC);
$triggers_arr = array();
foreach ($triggers_rows as $triggers_row) {
$trigger_id = $triggers_row['id'];
$trigger_title = $triggers_row['trigger_name'];
$trigger_description = $triggers_row['description'];
$trigger_setting = $triggers_row['setting'];
$trigger_user = $triggers_row['user_id'];
$trigger_placement = $triggers_row['placement'];
$trigger_date = $triggers_row['date_changed'];
触发器= t
CREATE TABLE `triggers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`trigger_name` varchar(70) COLLATE utf8_unicode_ci NOT NULL,
`setting` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(11) NOT NULL,
`placement` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`date_changed` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
用户= u
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(55) COLLATE utf8_unicode_ci NOT NULL,
`lastname` varchar(55) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(55) COLLATE utf8_unicode_ci NOT NULL,
`username` varchar(70) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`salt` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`joined` datetime NOT NULL,
`last_login` datetime NOT NULL,
`group` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=24 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_c
答案 0 :(得分:1)
对于sql代码,您只需要
SELECT
t.*,
u.id,
u.username
FROM triggers AS t
LEFT JOIN users AS u ON t.user_id = u.id