我试图列出注册到特定语言的所有用户的列表我一直在查看联接查询,但我无法弄清楚它是如何工作的,所有恶意尝试到目前为止都无法正常工作。这就是我到目前为止所做的:
<?php
$cursus2 = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM cursus JOIN Cursist"));
$result = mysqli_query($con, $cursus2);
$amount = mysqli_affected_rows($con);
for ($i = 0; $i < $amount; $i++) {
$Cursist = mysqli_fetch_array($result);
echo $Cursist['username']. "<br />";
}?>
我希望关闭与桥接表中的cursus连接的所有用户名的输出。
数据库结构:
**Cursist Table**
-------------
id username
-------------
1 name1
2 name2
3 name3
4 name4
**cursus Table**
-------------
id name
-------------
1 PHP
2 JAVA
3 HTML
4 RUBY
**Bridge**
-------------
Cursus_cursusCode Cursist_id
-------------
1 1
1 2
1 3
1 4
2 1
2 2
3 3
3 4
4 1
4 2
关闭的查询是我认为的那个:
SELECT * FROM cursus
JOIN cursist ON cursist.id=cursus.cursus_cursusCode
答案 0 :(得分:2)
您需要两个连接,而不是一个:
SELECT *
FROM Cursist t
INNER JOIN Bridge b
ON(t.id = b.cursist_id)
INNER JOIN Cursos s
ON(b.Cursus_cursusCode = s.id)
如果您只对用户名感兴趣,则无需从cursus表中选择任何内容,因此您可以这样做:
SELECT t.username
FROM Cursist t
INNER JOIN Bridge b
ON(t.id = b.cursist_id)
也可以用EXISTS()完成:
SELECT t.user_name
FROM Cursist t
WHERE EXISTS(SELECT 1 FROM Bridge B
WHERE t.id = b.cursist_id)
答案 1 :(得分:1)
尝试:
SELECT c2.username,c1.name
FROM bridge b, cursus c1, Cursist c2
WHERE b.Cursus_cursusCode=c1.id AND b.Cursist_id=c2.id
您可以查看here