Wednesday, February 2, 2022

[FIXED] SQL Query seems not to affect the same number of rows, Adding a count statement

Issue

I have made a query that looks like this

Query 1.

  SELECT zlec_status.nazwa                       AS Status, 
           piorytet.nazwa                          AS Priorytet, 
           Concat(koord.imie, ' ', koord.nazwisko) AS `Koordynator`, 
           Concat(zlec_adresy.miasto, ' - ', zlec_adresy.ulica, ' ', 
           zlec_adresy.oddzial) 
                                                   AS `adres`, 
           zlec_z_dnia,zlec_id, 
           zlec_nr, 
           zlec_do, 
           zlec_ogran, 
           awizacje, 
           awizacja_na_dzien, 
           termin_zamkniecia, 
           tresc, 
           uwagi 
    FROM   zlec 
           INNER JOIN koord 
                   ON zlec.koord = koord.id 
           INNER JOIN zlec_adresy 
                   ON zlec.zlec_addres = zlec_adresy.id 
           INNER JOIN piorytet 
                   ON zlec.priorytet = piorytet.id 
           INNER JOIN zlec_status 
                   ON zlec.status_zlecenia = zlec_status.id 

And the following one which is a ordinary one

Query 2.

SELECT * FROM zlec;

The thing is the first one returns ( affects by executing ) 48 rows where the second query returns 103 rows. What could be the possible cause of this?

I will also show you my dumb of the sql in case you would like to make a run on your own http://pastebin.com/cMPAtxCU .

Subquestion - quite no point starting of with a new question for that because its also connected with the row count affect.

Besides I was wondering how can I get into the first query a count(*) to get the affected rows - it has to be done in sql I cannot use php code for that, probably it would be good to use a limit 1 for the count.


Solution

With INNER JOIN, if one of your other tables, koord, zlec_adresy, piorytet and zlec_status is missing a record corresponding to a record in zlec, that record in zlec will not be in the result set. If you want every record in zlec to appear, you have to use LEFT JOIN. Check out:

http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/

For a pretty good explanation.



Answered By - Tripp Kinetics

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.