DBFlow icon indicating copy to clipboard operation
DBFlow copied to clipboard

subquery as iproperty

Open brwskitime opened this issue 10 years ago • 4 comments

Sorry having trouble figuring this out, but how would you do a query like this:

select
    a.id,
    (
        select count(*) from userInfo where user_id = a.id
    ) as infoTotal
from
    users a;

How do you pass in a subquery as an argument to Select()?

For this query, I'd just use a join, but I have something more complex in mind which I eventually want to create a view for. Thanks to anyone who can help.

brwskitime avatar Feb 17 '16 19:02 brwskitime

I've done this using

PropertyFactory.from(boolean.class, "(" + select().from(MyTable.class).getQuery() +")").as("myAlias")

It would be nice if there was a native PropertyFactory.from(Query query).

ghost avatar Feb 19 '16 14:02 ghost

What I'm doing is going with a StringQuery. My @Column fields get populated so seems to work. Although the generated _View class has no property fields.

@ModelView(database = MBDatabase.class, name = GamePlayerView.VIEW_NAME)
public class GamePlayerView extends BaseModelView<GamePlayerView> implements BaseColumns {

    public static final String VIEW_NAME = "view_02_game_players";

    @Column protected long _id;
    @Column protected long game__id;
    @Column protected long player__id;
    @Column protected int cash;
    @Column protected int titleTotal;
    @Column protected int totalValue;

    @ModelViewQuery
    public static final Query query = buildQuery();

    public long getId() {
        return _id;
    }

    public int getCash() {
        return cash;
    }

    private static Query buildQuery() {
        StringBuilder query = new StringBuilder();
       query.append("really complex query");

        StringQuery<GamePlayerView> sq = new StringQuery<>(GamePlayerView.class,query.toString());
        return sq;
    }
}

brwskitime avatar Feb 19 '16 22:02 brwskitime

@brwskitime, I found just now that you can make subquery like this:

SQLite.select(
    PropertyFactory.from(
        Contact.class, "(" + getYourComplexSubqueryString() + ")").as("subquery"))
.from(Plan.class);

which in my case generates

SELECT (SELECT `Contact`.`display_name` FROM `Contact` WHERE `Contact`.`_id`=`Plan`.`author_contact_id` ) AS `subquery` 
FROM `Plan`

gorodechnyj avatar Feb 29 '16 09:02 gorodechnyj

in develop now you can:

SQLite.select(
    PropertyFactory.from(someModelQueriable).as("subquery"))
.from(Plan.class);

agrosner avatar Mar 01 '16 19:03 agrosner