通常我会这样做以获得2张桌子
<?php
$select = "SELECT * FROM question ORDER BY id DESC LIMIT 0,20";
$query = $db->query($select);
while ($fetch = $db->fetch($query)) {
$uselect = "SELECT * FROM user WHERE id='".intval($fetch['q_user'])."' ";
$uquery = $db->query($uselect);
$ufetch = $db->fetch($uquery);
?>
Title : <?php echo $fetch['q_title']; ?>
User : <?php echo $ufetch['u_id']; ?>
<?php
}
?>
有一种简单的方法可以加入这个吗?
答案 0 :(得分:1)
嗯,你可以这样做:
SELECT *
FROM question
JOIN user ON question.q_user = user.id
ORDER BY question.id DESC
LIMIT 0, 20
我建议的一件事是明确列出列,因为任何重叠(Question.id和user.id)都是不明确的。只需SELECT question.id, user.id AS uid, ...
答案 1 :(得分:1)
SELECT * FROM question JOIN user ON question.q_user = user.id ORDER BY question.id DESC LIMIT 0, 20
有用的链接:http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html
答案 2 :(得分:0)
select * from question left join user on user.id = question.q_user order by question.id desc limit 0,20;
答案 3 :(得分:0)
SELECT * FROM question
LEFT JOIN user ON user.id = question.q_user
ORDER BY question.id DESC LIMIT 0,20
答案 4 :(得分:0)
此查询应该是正确的:
create table questions
(
question_id bigint unsigned auto_increment primary key,
user_id bigint unsigned not null,
title varchar(255),
)engine=innodb;
create table users
(
user_id bigint unsigned auto_increment primary key,
name varchar(255) not null
)engine=innodb;
// your query
select q.* from questions q
inner join users u where u.user_id = q.user_id
order by q.question_id desc
答案 5 :(得分:0)
是的,我假设您想要返回提出问题的用户,因为您存储了q_user,那么您需要执行一些SQL:
“SELECT q.q_title,u.u_id FROM question q JOIN user u ON(q.q_user = u.u_id)”
您可以将限制等应用于此查询。