简体   繁体   中英

Do I need to link tables together when making a MySQL query?

If I have a database(sakila) with multiple tables, and I want to query multiple columns that relate to each other do I need to use keywords like

SELECT city.city, actor.first_name, actor.last_name
FROM city, actor, staff, address, inventory, film_actor, store
WHERE city.city_id = address.city_id AND
address.address_id = staff.address_id AND
staff.staff_id = store.store_id AND
store.store_id = inventory.store_id AND
inventory.film_id = film_actor.film_id AND
film_actor.actor_id = actor.actor_id

or can I just select them without linking the keys together like this:

SELECT city.city, actor.first_name, actor.last_name
FROM city, actor

EDIT:
So, since I want to see which cities the actors are from, I should use an inner join because a cross join will just match every city to every actor regardless if they actually relate?

Yes. You will have to use a JOIN command.

Ex.

SELECT c.city, a.first_name, a.last_name
FROM city c 
INNER JOIN address ad ON c.city_id = ad.city_id 
INNER JOIN staff s ON ad.address_id = s.address_id
INNER JOIN store st ON s.store_id = st.store_id
INNER JOIN inventory i ON st.store_id = i.store_id
INNER JOIN film_actor fa ON i.flim_id = fa.film_id
INNER JOIN actor a ON fa.actor_id = a.actor_id

What do you mean by multiple columns that relate to each other? can you explain further, the normal way of making a select query is like this

$sql= "Select column name FROM tablename ";

or be specific like

$sql="Select column name FROM tablename Where column name LIKE '%%' "; 

you can make query with related fields by making another query for example $sql, $sql2 and so on.

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