Search code examples
phpmysqldatatableconditional-statementscrud

Getting a row based on the condition


Been circling around trying to find a solution to this problem. I already searched for it and had no luck finding one.

I have 2 tables which are related

entry table

id entry_name entry_qty entry_group entry_owner high_bet early_finish
1 Test1 3 1 Test1 0 1
2 Test2 3 NULL Test 2 0 1
3 Test3 3 NULL Test3 0 1
4 Test4 3 NULL Test 4 0 0

entries table

id parent_id enties_name entries_weight fought
1 1 Test1__1 1011 NULL
2 1 Test1__2 1011 NULL
3 1 Test1__3 1011 NULL
4 2 Test2__1 1011 NULL
5 2 Test2__2 1011 NULL
6 2 Test2__3 1011 NULL
7 3 Test3__1 1011 NULL
8 3 Test3__2 1011 NULL
9 3 Test3__3 1011 NULL
10 4 Test4__1 1011 NULL
11 4 Test4__2 1011 NULL
12 4 Test4__3 1011 NULL

This is the query I want to achieve but not sure how to convert it to mysql or php script:

randomly select(1) parent_id from entries if entry.early_finish is 1 (prioritize) or 0 (less priority but will be picked when there is no 1 left) then add a value to fought if picked.

Then;

Randomly select(1) parent_id from entries if entry.early_finish is 1 (prioritize) or 0 (less priority but will be picked when there is no 1 left) AND entry.group_id is not equal to the first query then add a value to fought if picked.

This way, 2 random rows will be picked and this will be the match.

Hoping someone here can save me. Thanks!


Solution

  • SELECT
        es.id,
        es.parent_id,
        e.entry_name as parent_name,
        es.entries_name,
        es.entries_weight,
        es.fought
    FROM
        entries es
    LEFT JOIN
        entry e
    ON
        es.parent_id = e.id
    WHERE
        e.early_finish = (
            CASE
                WHEN (SELECT count(id) FROM entry WHERE early_finish=1) > 0 THEN 1
                ELSE 0
            END
        )
    AND
        es.fought = 0
    ORDER BY RAND()
    LIMIT 1;