简体   繁体   中英

How to filter a table in SQL by a foreign key?

I am making an website where bike repairs can be registered. It works, but now I am fine tuning. I have a MySQL database with a table called "Reparation", "Customer" and "bike"

In bike, there is a unique ID with the model, brand, and so on. In Customer, there are the customerID, Customer name, adress, and so on. In Reparation I can select a customer and a bike, so they are related, that's good too :).

When I select a customer in reparation, I want to see only his bikes. So, when the customer has two bikes, I want to select the customer and see the two bikes only (or the uniqueID'S from them).

Now I select a customer, and I see all the bikes of all the customers. How do I do this, in phpMyAdmin or PHP? Both are good, but better phpMyAdmin if possible..

Since you havent provided the table structure, we can only give you example:

So you can try something like:

SELECT * FROM Reparation WHERE customer_id = selected_customer_id;

Since one Customer can have multiple Bikes, and one Bike belongs to one customer, you should store the CustomerID in your bike table ( 1-to-many relationship ).

Bike                                     Customer
  + bikeID                                 + customerID
  + bikeBrand                              + customerAddress
  ...                                      ...
  + customerID                             

And then, to select all the bikes belonging to a customer whose ID is X :

SELECT bikeID FROM Bike WHERE customerID = X;

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