I am trying to write a SQL query in Delphi, but yet without luck.
I have two tables, the first one holds personal data, the second one holds information about purchased goods.
My query works fine when I connect the two tables with WHERE clause (my key is person_id).
But I would like to add records to my query that have no personal data, just someone purchased the goods, they don’t display.
So in those records where there isn’t any personal information I need to have empty strings or null values.
Is it possible to do in one SQL query?
Edit: Here is the working version, but this doesn’t contain the second table’s values that are not related to the first table.
Query1.SQL.Add ('SELECT idcard, vnev, knev, kapcs, ');
Query1.SQL.Add ('bsz, bt, kidate, ervvege, alkalmak FROM "'+adathely+'", "'+berlethely+'" ');
Query1.SQL.Add ('WHERE ("'+adathely+'".idcard = "'+berlethely+'".idcard) ');
//from here only filtering occurs
Query1.SQL.Add ('AND kidate >= "'+IntToStr(DateToInt(filterdate1.Text))+'" ');
Query1.SQL.Add ('AND ervvege <= "'+IntToStr(DateToInt(filterdate2.Text))+'" ');
Query1.SQL.Add ('AND CAST(bsz AS CHAR(6)) LIKE '''+filterbsz.Text+'%'' ');
Query1.SQL.Add ('AND ((LOWER(vnev) LIKE ''%'+filtername.Text+'%'') OR (LOWER(knev) LIKE ''%'+filtername.Text+'%'')) ');
Query1.SQL.ADD ('ORDER BY vnev ASC ');
A little explanation: table1 is “adathely” table2 is “berlethely”
Both tables contain the field ‘idcard’, but in table2 there are records that do not have value in this field, but i also would like to display them in my stringgrid.
I think you wrote a query like this:
and if person_id is present in Table1 but not in Table2, no record will appear.
Try a LEFT JOIN instead:
This will show every record in Table1 even if it is not correlated to a record in Table2.
EDIT: if a left join is not enough, you probably need a FULL OUTER JOIN. If your DBMS does not support FULL OUTER JOIN, you could simulate it using this:
and since there are a lot of conditions in the where clause, i’d suggest you to write your query like this:
just to make things more readable.