Foros aprenderaprogramar.com

Aprender a programar => C, C++, C#, Java, Visual Basic, HTML, PHP, CSS, Javascript, Ajax, Joomla, MySql y más => Mensaje iniciado por: gatoher en 02 de Junio 2016, 12:01

Título: Consulta mysql para obtener el primer registro en una relación uno a muchos
Publicado por: gatoher en 02 de Junio 2016, 12:01
Hola a todos, a ver estoy haciendo una consulta de varias tablas. Una de ella se guardan imagenes de un usuario, relacion tipica uno a muchos.

Yo solo estoy interesado que me devuelva una imagen aunque el usuario tenga 10. ¿Como se podría hacer eso? Quiero limitar ese campo a 1.

select u.nick, prov.nombre, post.fechaPost, post.titulo, post.comentario, img.ruta 'aqui solo quiero que me devuelva 1 imagen'
from usuario AS u, post AS post, provincias AS prov, imagenes AS img  order by post.fechaPost
Título: Re:Consulta mysql de varias tablas donde una columna devuelve varios campos
Publicado por: gatoher en 02 de Junio 2016, 15:09
(http://)   A ver, estoy algo perdido. Voy a subir una imagen del modelo. Lo que yo ando buscando es en una select saber por ejemplo:

   De la tabla usuario el nick.
   De la tabla imagenes la ruta
   De la tabla post el titulo y comentario.
 
   Todo ello por orden de fecha descendiente.
   
   A ver si alguien esta puesto en mysql.  ;)

Título: Re:Consulta mysql para obtener el primer registro en una relación uno a muchos
Publicado por: César Krall en 11 de Junio 2016, 18:28
Hola, para que te devuelva solo x unidades usarías limit

select u.nick, prov.nombre, post.fechaPost, post.titulo, post.comentario, img.ruta
from usuario AS u, post AS post, provincias AS prov, imagenes AS img 
order by post.fechaPost
LIMIT 1


Si lo que quieres es obtener muchos registros donde solo obtengas el primer registro de una relación uno a muchos puedes guiarte por el siguiente ejemplo (la verdad es que no es muy sencillo pero con un poco de tiempo se hace):

Base de datos de ejemplo:

Código: [Seleccionar]
<!--- SQL to create and populate the data tables. --->
<cfsavecontent variable="strSQL">
<!--- Create table for contact data. --->
DECLARE @contact TABLE (
id INT IDENTITY( 1, 1 ),
name VARCHAR( 20 )
);

<!---
Create table for phone data (each phone number will be
associated with exactly one contact).
--->
DECLARE @phone TABLE (
id INT IDENTITY( 1, 1 ),
name VARCHAR( 20 ),
ext VARCHAR( 7 ),
is_preferred BIT,
contact_id INT
);



<!--- Populate the contact data. --->
INSERT INTO @contact
(
name
)(
SELECT 'Ben Nadel' UNION ALL
SELECT 'Maria Bello' UNION ALL
SELECT 'Jodie Foster' UNION ALL
SELECT 'Christina Cox'
);


<!--- Populate the phone data. --->
INSERT INTO @phone
(
name,
ext,
is_preferred,
contact_id
)(
<!--- Ben's numbers. --->
SELECT '212-555-BEN1', '', 1, 1 UNION ALL
SELECT '212-555-BEN2', '123', 0, 1 UNION ALL
SELECT '212-555-BEN3', '', 0, 1 UNION ALL

<!--- Maria's phone numbers. --->
SELECT '917-555-MAR1', '', 0, 2 UNION ALL
SELECT '917-555-MAR2', '', 0, 2 UNION ALL
SELECT '917-555-MAR3', '', 0, 2 UNION ALL

<!--- Christina's phone numbers. --->
SELECT '202-555-CHR1', '', 0, 4 UNION ALL
SELECT '202-555-CHR2', '15', 1, 4
);
</cfsavecontent>

Join standard:

Código: [Seleccionar]
<!--- Query for contacts and their phone numbers. --->
<cfquery name="qContact" datasource="#REQUEST.DSN.Source#">
    <!--- Create the SQL data tables and populate. --->
    #PreserveSingleQuotes( strSQL )#
    <!--- Select contacts as their numbers. --->
    SELECT
        c.name,
        <!--- Phone data. --->
        ( p.name ) AS phone_number,
        ( p.ext ) AS phone_ext,
        (
            ISNULL(
                p.is_preferred,
                0
            )
        ) AS is_preferred
    FROM
        @contact c
    LEFT OUTER JOIN
        @phone p
    ON
        c.id = p.contact_id
    ORDER BY
        c.name ASC
</cfquery>


<!--- Dump out contacts and their phone numbers. --->
<cfdump
    var="#qContact#"
    label="Contact Phone Numbers"
/>

Seleccionar el primero de los registros cuando hay varios:

Código: [Seleccionar]
SELECT TOP 1
    p.id,
    p.name,
    p.ext,
    p.is_preferred
FROM
    @phone p
WHERE
    p.contact_id = 1
ORDER BY
    p.is_preferred DESC,
p.id ASC

Consulta para obtener solo uno de los números de teléfono (el preferido):

Código: [Seleccionar]
<!--- Query for contacts and their phone numbers. --->
<cfquery name="qContact" datasource="#REQUEST.DSN.Source#">
    <!--- Create the SQL data tables and populate. --->
    #PreserveSingleQuotes( strSQL )#
    <!--- Select contacts as their numbers. --->
    SELECT
        c.name,
        <!--- Phone data. --->
        ( p.name ) AS phone_number,
        ( p.ext ) AS phone_ext,
        (
            ISNULL(
                p.is_preferred,
                0
            )
        ) AS is_preferred
    FROM
        @contact c
    LEFT OUTER JOIN
        @phone p
    ON
        (
                c.id = p.contact_id
            AND
                <!---
                    As part of the JOIN condition, make sure
                    that this ID of the phone record we return
                    is equal to the *most* preferred one for
                    that user.
                --->
                p.id = ISNULL(
                    (
                        SELECT TOP 1
                            p2.id
                        FROM
                            @phone p2
                        WHERE
                            <!--- Tie to current user record. --->
                            p2.contact_id = c.id
                        ORDER BY
                            p2.is_preferred DESC,
                            p2.id ASC
                    ),
                    0
                )
        )
    ORDER BY
        c.name ASC
</cfquery>


<!--- Show contact with max of ONLY one phone number. --->
<cfdump
    var="#qContact#"
    label="Contact Phone Numbers (Max: 1)"
/>

Con esto obtenemos solo un número de teléfono cuando el contacto tiene varios números de teléfono

Saludos!