Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

query without derived table

Tags:

mysql

jpa-2.0

I have two tables flat and usertoflat I want to fetch all data from flat table with where condition on usertoflat table.

I am using JPA but I didn't found derived table query in jpa below is my native sql query.

Table Flat

flat_id | flat_no | status
   1    |   1001  |   1
   2    |   1002  |   1
   3    |   1003  |   1
   4    |   1004  |   1


Table usertoflat

usertoflat_id | Name    | flat_id | status
      1       | ABC     |   1     |   1
      2       | ABC     |   1     |   2
      3       | XYZ     |   2     |   1
      4       | PQR     |   3     |   1


Required output

flat_id | flat_no | Name
   1    |   1001  | ABC
   2    |   1002  | XYZ
   3    |   1003  | PQR
   4    |   1004  | 

Query with derived table

select f.flat_id, f.flat_no, uf.name from flat f left join 
(select * from usertoflat where status  = 1 )
as uf on f.flat_id = uf.flat_id 

How to achieve the same without using derived table, since I am using JPA and I didn't found derived table in JPA so if I can get the native sql query I will convert the same in JPA query.

like image 573
pise Avatar asked Sep 05 '16 07:09

pise


People also ask

Why we use derived table in SQL?

Derived Tables in SQL Server. A derived table is a technique for creating a temporary set of records which can be used within another query in SQL. You can use derived tables to shorten long queries, or even just to break a complex process into logical steps.

Is it possible to have a SELECT statement without WHERE clause?

Although the SQL standard doesn't allow a SELECT statement without a FROM clause, pretty much every other database does support the construct of selecting and expression without a FROM clause.

What's the difference between a view and a derived table?

The performance of the view is faster from derived table , as we can be materialized. And whenever an object from view is selected it will going to extract the respective object only. However for derived table all the columns will be executed in the database. So this will impact the performance of the report.


2 Answers

You can simply make a left join instead of creating a subquery

SELECT
    f.flat_id,
    f.flat_no,
    uf.name
FROM flat f
LEFT JOIN usertoflat uf ON  f.flat_id = uf.flat_id AND uf.status = 1;

See Demo

Or

SELECT
    f.flat_id,
    f.flat_no,
    uf.name
FROM flat f
LEFT JOIN usertoflat uf ON  f.flat_id = uf.flat_id 
WHERE uf.status IS NULL OR uf.status = 1;

See Demo

like image 186
1000111 Avatar answered Sep 23 '22 08:09

1000111


I think this is what you need?

select f.flat_id, f.flat_no, uf.name from flat f left join 
usertoflat uf on f.flat_id = uf.flat_id and uf.status  = 1 
like image 45
Jens Avatar answered Sep 22 '22 08:09

Jens