Jump to content

Query with optional parameter?


Go to solution Solved by requinix,

Recommended Posts

Lets say I have two tables:

 

Table1

 

Id Name

1 Joe

2 Greg

3 Susan

4 Max

 

 

Table2

 

Uid comment

2    Good customer

4    Great guy

 

 

What I want to do is list all elements of Table 1, and if Table1.Id = Table2.Uid I want to select this comment. If comment does not exist give blank field.

 

Result should be:

1 Joe 

2 Greg Good customer

3 Susan

4 Max Great Guy

 

 

I can't figure out how to do it, if I write:

select
table1.Id,
table1.Name,
table2.comment

where
table1.id=table2.Uid

It gives me only users 2 and 4.

 

Do you have any ideas?

Link to comment
https://forums.phpfreaks.com/topic/280705-query-with-optional-parameter/
Share on other sites

  • Solution

Use a proper JOIN in your query, not the form where you specify multiple tables in the FROM.

SELECT
table1.Id,
table1.Name,
table2.comment
FROM table1
JOIN table2 ON table1.Id = table2.Uid
That will still give you 2 and 4. Now turn it into a LEFT JOIN

...FROM table1
LEFT OUTER JOIN table2 ON table1.Id = table2.Uid...
The LEFT means that for every row in the "left" table (table1) there may not be corresponding rows in the "right" table (table2). With the default INNER JOIN, if there are no matching rows then the row from the left table is thrown out; with an OUTER JOIN (be it LEFT or RIGHT) the row is kept and the missing values become all NULL.

Id | Name  | comment
---+-------+--------
 1 | Joe   | NULL
 2 | Greg  | Good customer
 3 | Susan | NULL
 4 | Max   | Great Guy
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.