Multiple SQL SELECT

0

I have 5 tables with many records. Each table has "Date" columns, in which there may be only one date per user (the last date on which a user modified their profile is stored, for example) or many dates per user (the dates on which the user has posted one or more ads). How could I make a query to select all the dates of each table taking into account the user?

At the moment I have this

SELECT DISTINCT Acept_Date, Marc_Fec, Cont_Mod, Emp_Mod, Dir_Mod
FROM anunciosaceptados, anunciosmarcados, contacto, datos_empresa, direcciones
WHERE Acept_usu = 'gmarsi' 
AND Marc_Usu = 'gmarsi'
AND Con_Usu = 'gmarsi'
AND Emp_Usu = 'gmarsi'
AND Dir_Usu = 'gmarsi'

and it is not working for me, because it shows me many repeated records as seen in the image. The tables that end in _Mod only save one date per user and show me many more

    
asked by gmarsi 15.05.2017 в 09:36
source

2 answers

1

If you are doing DISTINCT NO there can be repeated records, the DISTINCT works in a similar way to a GROUP BY for each field, if there was one I would dare to say that it is a millisecond problem and that the dates are still different, only that these milliseconds are not shown. On the other hand, if each table can have from 1 to N different dates, that is to say if in each table the dates are not repeated, and in short you want to see them all, it is not necessary to make a GROUP BY or a DISITNCT, what happens, is that making a Cartesian product between tables will undoubtedly repeat dates in one table for each date other than another of the tables. Visualizing them in this way does not seem like the best idea, a more optimal view would be the following:

SELECT  'anunciosaceptados' AS 'Tabla',
    'Acept_Date'        AS 'Campo',
    Acept_Date      AS 'Valor'
    FROM anunciosaceptados
    WHERE Acept_usu = 'gmarsi' 

UNION

SELECT  'anunciosmarcados',
    'Marc_Fec',
    Marc_Fec
    FROM anunciosmarcados
    WHERE Acept_usu = 'gmarsi' 

UNION

SELECT  'contacto',
    'Cont_Mod',
    Cont_Mod
    FROM contacto
    WHERE Con_Usu  = 'gmarsi' 


UNION

SELECT  'datos_empresa',
    'Emp_Mod',
    Emp_Mod
    FROM datos_empresa
    WHERE Emp_Usu = 'gmarsi' 

UNION

SELECT  'direcciones',
    'Dir_Mod',
    Dir_Mod
    FROM direcciones
    WHERE Dir_Usu = 'gmarsi' 

The idea of this query is to return as was your question, all the dates of each table, in a single column in this case, also indicating the table and the field to which the date refers. If you had repeated dates in each table, simply add a DISTINCT or GROUP BY

    
answered by 15.05.2017 / 16:39
source
1

The problem is that you probably do not have the normalized tables and you have a lot of redundancy, generating many repeated fields. It is normal to leave the _mod fields many times since they will leave as many times as dates from the other fields, those that can exit several times . If you do a GROUP BY surely lose information.

    
answered by 15.05.2017 в 10:02