Usage of AND vs WHERE clause in SQL

前端 未结 3 1682
囚心锁ツ
囚心锁ツ 2021-01-06 22:39

I am working on PHP page that connects with Oracle. I came across this SQL and I am not sure it is doing what is supposed to, so I thought I would

相关标签:
3条回答
  • 2021-01-06 23:06

    Am I right?

    No. This query:

    select tableA.id, tableA.name, tableB.details 
    from tableA
    left join tableB
    on tableB.id = tableA.id
    and tableB.logId = '<logged_in_user>'
    

    Is very different from:

    select tableA.id, tableA.name, tableB.details 
    from tableA
    left join tableB
    on tableB.id = tableA.id
    where tableB.logId = '<logged_in_user>'
    

    It's the criteria for joining.

    In the first case, you take from A, then join with B when there's a matching id and a logId, else leave details null.

    In the second, you take from A, then join with B when there's a matching id, else leave details null, and then you keep only rows from A where there's a B match that has a logId -- eliminating rows from A in the process, and de facto turning it into an inner join.

    0 讨论(0)
  • 2021-01-06 23:06

    If you only want results with values in both tables what you really want is an inner join. Once you have that, it doesn't really matter where you filter results out.

    0 讨论(0)
  • 2021-01-06 23:25

    Now when I log in as a user who does not have entries in tableB, I am still getting records when this query runs.

    Simply change the query to use an inner join like this:

    select tableA.id, tableA.name, tableB.details 
    from tableA
    inner join tableB ...
    

    and here is the definition of left join from Oracle:

    The LEFT JOIN (also called LEFT OUTER JOIN) keyword returns all rows from the left table (table_name1), even if there are no matches in the right table (table_name2).

    whereas the definition of the inner join is:

    The INNER JOIN keyword return rows when there is at least one match in both tables.

    0 讨论(0)
提交回复
热议问题