Filter query using foreign key

1

I have the following tables:

Tabla 1        
----------
id
*fk_ciudades
datoX1
datoX2

Tabla 2
----------
idCiudades
nombreCiudades

And I want to make a query that selects one of the rows of Table 1 , when a variable x that I pass, is equal to the name of one of the cities in Table 2 . The problem is that I do not know how to build WHERE to achieve that.

I thought that putting "WHERE *fk_ciudades = $varx" was enough to reference the names of the cities in Table2, but I have not succeeded. It's possible? Or am I being a victim of bad plan planning?

    
asked by Gundwane 18.02.2017 в 23:17
source

2 answers

0

I leave this simple outline. You can extend it if you want to provinces, countries, etc. The query shows people whose id_city = 1.

SQL Fiddle

MySQL 5.6 Schema Setup :

CREATE TABLE personas
    ('id_persona' int, 'nombre' varchar(150), 'id_ciudad' int)
;

INSERT INTO personas
    ('id_persona', 'nombre', 'id_ciudad')
VALUES
    (1, 'Pedro', 1),
    (2, 'Santiago', 2),
    (3, 'Juan', 3),
    (4, 'Andrés', 1)


;

CREATE TABLE ciudades
    ('id_ciudad' int, 'ciudad' varchar(150), 'id_provincia' int)
;

INSERT INTO ciudades
    ('id_ciudad', 'ciudad', 'id_provincia')
VALUES
    (1, 'Galilea', 1),
    (2, 'Betsaida', 2),
    (3, 'Patmos', 3)
;

Query 1 :

SELECT
  p.nombre, c.ciudad
FROM
  personas p
JOIN ciudades c
  ON p.id_ciudad=c.id_ciudad
WHERE p.id_ciudad=1

Results :

| nombre |  ciudad |
|--------|---------|
|  Pedro | Galilea |
| Andrés | Galilea |
    
answered by 19.02.2017 / 02:41
source
1

First of all, to be able to do what you want from:

  

I want to make a query that selects one of the rows in Table 1, when a variable x that I pass, is equal to the name of one of the cities in Table 2.

You have to do a JOIN . Suppose I want to select the row according to the column id , and I will also suppose that it is of type numeric . I also suppose that the columns with keys, in table1 is fk_cities and in table2 it is idCities

SELECT id.Tabla1 
FROM Tabla1 INNER JOIN Tabla2 ON Tabla1.[*fk_ciudades]=Tabla2.[idCiudades]
WHERE Tabla2.nombreCiudades='nombre de la ciudad que le pases'

The tables must be correctly related to do this operation, it is necessary to say.

    
answered by 18.02.2017 в 23:53