如何根据另一个表中的值访问表上的行?

时间:2017-02-25 19:46:37

标签: mysql sql

我正在使用MySQL做一个迷你项目。我遇到了以下问题:

我创建了2个表,studentbook,分别为6列和5列。

    mysql> select * from book;
+--------+------+------------+---------+------+
| bookid | Name | Authorname | edition | cost |
+--------+------+------------+---------+------+
| cc12   | dbms | guna       |       5 |  500 |
| cc34   | CA   | fasil      |       5 |  600 |
| cs113  | OS   | rohan      |       3 |  300 |
| cs12   | AI   | ganesh     |       2 | 1000 |
| cs343  | c#   | jackesh    |       4 |  300 |
+--------+------+------------+---------+------+
5 rows in set (0.00 sec)

mysql> select * from studentbook;
+-----+--------+-----------+
| Sno | bookid | Studid    |
+-----+--------+-----------+
|   1 | cc12   | 14vec1088 |
|   2 | cs113  | 14vec1099 |
|   3 | cc34   | 14vec1132 |
|   4 | cs343  | 14vec2011 |
|   5 | cs12   | 14vec100  |
+-----+--------+-----------+
5 rows in set (0.00 sec)

现在,当我输入表studid中提到的任何studentbook时(这是由PHP在后端执行),它应该显示与相应{{1}相关联的书籍的详细信息}来自表studid

如何使用MySQL Query执行上述操作?

2 个答案:

答案 0 :(得分:3)

这可能有用。

SELECT * FROM book
WHERE bookid IN 
(SELECT bookid FROM studentbook 
WHERE studid = "[Id of which you want book]");

答案 1 :(得分:1)

这可以满足您的需求。

SELECT b.* 
FROM book b
INNER JOIN studentbook sb on b.bookid = sb.bookid
WHERE sb.Studid = [your id]