简体   繁体   中英

How to access a row on a table based on a value from another table?

I am doing a mini project using MySQL. I came with the following problem:

I created 2 tables, student and book with 6 and 5 columns respectively.

    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)

Now, when I enter any of the studid mentioned in the table studentbook (This is performed by PHP in the backend) it should display the details of book associated with the respective studid from the table book .

How can I perform the above using MySQL Query?

This might be work.

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

This should get you what you need.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM