MySQL通过id组合了两个表

时间:2015-09-04 14:14:28

标签: php mysql

我有两张桌子:

alpha

id  |  title  |  catid

1   |  winter |  105
2   |  summer |  105
3   |  fall   |  20
4   |  spring |  12

beta

id  |  author

1   |  john
2   |  mike
3   |  bill


结果 - 我想通过匹配上面两个表中的id来生成下表。只使用那些colums" catdid"是105。

id  |  author |  title

1   |  john   |  winter
2   |  mike   |  summer


我有以下查询:

$table_alpha = "alpha";
$table_beta = "beta";

$sql = "
SELECT id, title, catid, author 
FROM $table_alpha, $table_beta 
WHERE catid = 105
…
???
…
";

有什么想法吗?感谢。

3 个答案:

答案 0 :(得分:2)

我在手机上写这个,所以我希望它有效,但你真的需要使用JOIN

$table_alpha = "alpha";
$table_beta  = "beta";

$sql = "
    SELECT id, title, catid, author
    FROM $table_alpha
    JOIN $table_beta USING(id) 
    WHERE catid = 105
";

USING子句告诉查询要处理要加入的事件id。这应该可以安全地通过名称查询它而不说明要检索哪个id(我希望我可以验证这个,但我手机上没有SQL :-p)

答案 1 :(得分:1)

您的查询非常接近,您需要使用带有条件的JOIN:

$table_alpha = "alpha";
$table_beta = "beta";

$sql = "
SELECT $table_alpha.id, title, author 
FROM $table_alpha
JOIN $table_beta 
ON $table_alpha.id=$table_beta.id
WHERE catid = 105
"

答案 2 :(得分:0)

这应该做的工作:

SELECT a.id, b.author, a.title
FROM alpha AS a
INNER JOIN beta AS b
ON a.id = b.id
WHERE a.catid = 105;