0

I'm having problems with a SELECT query, which instead of returning me a single value, gives me too many. The query below:

            SELECT costi.id, costo, descrizione, categoria
            FROM costi 
            INNER JOIN categorie 
            WHERE costi.id = 140

The query fishes data from a DB with two tables (costi and categorie) db structure

The problem I'm having is that: If, for example, I run the query on PHP my admin (by entering instead of $ _POST ['id'], the ID of a cost like 140) instead of just going back one row with the associated data, It comes back two rows (one for each category I've created). query result

They are identical rows, with the same values, except for the category field that is different. I need back just one row with the correct data.

  • 1
    You're not specifying any condition for the join. In other words, you're missing an `on` statement following the join. – Mitya Aug 10 '17 at 09:31
  • Please specify some conditions to join. Otherwise it will populate like now only – Pranav MS Aug 10 '17 at 09:39
  • If you don't specifying a ON statement your INNER JOIN will work as a CROSS JOIN instead makes sense that you get duplicated records. No body explained why it happens so i will explain it. – Raymond Nijland Aug 10 '17 at 09:55

6 Answers6

0

Looking to your query result ..

You could use a group_concat for get the result in one row

   SELECT  costo, descrizione, group_concat(categoria)
        FROM costi 
        INNER JOIN categorie 
        WHERE costi.id = 140
 group by   costo, descrizione
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

Looks like it should be:

SELECT costi.id, costo, descrizione, categoria
FROM costi 
INNER JOIN categorie
    ON costi.id = categorie.id --note the join condition
WHERE costi.id = 140
SierraOscar
  • 17,507
  • 6
  • 40
  • 68
0

You need to JOIN the 2 tables using the foreign key in the JOIN statement

SELECT costi.id, costo, descrizione, categoria
FROM costi 
    INNER JOIN categorie ON categorie.id = costi.idcatagoria
WHERE costi.id = 140

Now the query knows which rows in the 2 tables are related to each other

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
0

There can be 2 approaches:

  1. Use the following query avoiding INNER JOIN:

        SELECT h.id, h.costo, h.descrizione, i.categoria
        FROM costi h, categorie i 
        WHERE h.id = 140 and h.idcategoria=i.id
    
  2. You can use GROUP BY with INNER JOIN

Chinmay jain
  • 979
  • 1
  • 9
  • 20
0

use the following query avoiding INNER JOIN:

 SELECT h.id, h.costo, h.descrizione, i.categoria
    FROM costi h, categorie i 
    WHERE h.id = 140 and h.idcategoria=i.id
SAH
  • 31
  • 5
-1

specifying any condition for the join. like table.id on ...

specify condition then you will get limited results