我使用下表:
我的想法是,当我输入带有artist_id的艺术家页面时,我可以使用该ID加载相关的艺术家。以下代码有效,但如何将其放在单个查询中?我无法理解。
要将related_artists与艺术家联系起来,我创建了以下代码:
$sql = "SELECT related_artist_id FROM related_artists WHERE artist_id = 1";
$res = mysqli_query($db, $sql);
if (!$res) {
echo "Er is een fout opgetreden.";
exit;
} else {
while ($row = mysqli_fetch_array($res)) {
$query = 'SELECT * FROM artists WHERE artist_id = '.$row["related_artist_id"];
print_r($query."<br />\n");
$result = mysqli_query($db, $query);
if ($result) {
while ($test = mysqli_fetch_array($result)) {
echo $test["lastName"]."<br />\n";
}
} else {
echo "It doesn't work";
exit;
}
}
}
答案 0 :(得分:2)
你可以使用LEFT JOIN,试试这个:
SELECT b.*
FROM related_artist a
LEFT JOIN artists b
USING(artist_id)
WHERE a.artist_id = 1
应该从艺术家返回*,其中我aliased艺术家为b,related_artist为。
没有测试,是否适用于您/返回预期结果?
答案 1 :(得分:2)
你可以尝试:
select *
from artists
where artist_id in (
select related_artist_id
from related_artists
WHERE artist_id = 1
);
答案 2 :(得分:0)
SELECT * FROM artists where artists.arist_id = 1
INNER JOIN related_artist ON related_artist.artist_id = artists.artist_id
这提供了两个表的artist_id列的连接,其中artist_id = 1.我不确定您是否需要内部或左侧连接