¿Cómo unirse a una sola columna?
SELECT * FROM table1
LEFT JOIN table2
ON table1.id = table2.table1_id
WHERE table1.id = 1
Necesito unir solo una columna de la tabla 2, digamos first_name. ¿Cómo puedo hacer eso?
3 answers
Suponiendo que quiere decir "seleccione una columna de la tabla 2":
SELECT table1.*, table2.first_name
FROM table1
LEFT JOIN table2
...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-28 06:27:31
Quieres decir además de tu consulta ya indicada:
SELECT * FROM table1
LEFT JOIN table2
ON table1.id = table2.table1_id
WHERE table1.id = 1 and table1.first_name = table2.first_name
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-28 06:30:18
La respuesta aceptada es la respuesta correcta, pero me he encontrado con un extraño error cuando las tablas están en dos bases de datos diferentes:
Asumiendo que tabla1 está en database1 y tabla2 está en database2. Inicialmente he intentado esto:
SELECT *, database2.table2.first_name FROM table1
LEFT JOIN database2.table2
ON database1.table1.id = database2.table2.table1_id
WHERE table1.id = 1
Lo extraño es que si pruebo esta consulta desde PHP PDO no hubo errores, pero el resultado contenía todas las columnas de database2.tabla2 (solo se espera la columna first_name).
Pero si he intentado la misma consulta desde phpmyadmin tiene un error sintax:
Cuadro " base de datos2.la tabla 1 ' no existe
Por lo tanto, para resolver eso, entonces todas las bases de datos deben especificarse implícitamente así :
SELECT database1.table1.*, database2.table2.first_name FROM database1.table1
LEFT JOIN database2.table2
ON database1.table1.id = database2.table2.table1_id
WHERE database1.table1.id = 1
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-26 19:01:16