Samuel
Samuel

Reputation: 18586

Complex query over two tables

I have two tables:

table1:
id
--
1
2
3

table2: (left out primary index)
id2 | cond
----------
3   | 1
3   | 0
2   | 1
2   | 1
2   | 0

I would need to construct a query that implicitly calculates this intermediary table:

temp:
id | c1 | c2
------------
1  | 0  | 2
2  | 2  | 2
3  | 1  | 2

with c1 = countRows(id2 == id && cone == 1) and c2 == countRows(id2 = 2 && cond == 1).

and then selects SELECT id FROM temp ORDER BY ABS(c1 - c2)*RAND().

My current try is kind of like:

SELECT id, COUNT(t1.id2) AS c1, COUNT(t2.id2) AS c2
FROM table1 LEFT JOIN (table2 AS t1) ON id=t1.id2 LEFT JOIN (table2 AS t2) ON t2.id2=2
WHERE t1.cond=1 AND t2.cond=1
GROUP BY t1.id2
ORDER BY ABS(c1 - c2)*RAND()
LIMIT 1

Which has multiple problems:

  1. It doesn't select rows with no entry in table2
  2. It doesn't correctly count
  3. There seems to be a problem with group columns (c1, c2) in the ORDER BY part 3.

Help would be appreciated.


Update:

Upvotes: 0

Views: 54

Answers (2)

shmosel
shmosel

Reputation: 50746

SELECT t1.id, SUM(IFNULL(t2.cond, 0) = 1) AS c1, (SELECT SUM(cond = 1) FROM table2 WHERE id2 = 2) AS c2
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id2
GROUP BY t1.id
ORDER BY ABS(SUM(IFNULL(t2.cond, 0) = 1) - c2) * RAND();

Upvotes: 2

J A
J A

Reputation: 1766

Let's see if the first part of your query is returning valid results..

SELECT
    t1.id AS id
    COUNT(t2.id2) AS c1
    COUNT(CASE WHEN t3.id2 = 2 THEN t3.id2 ELSE NULL END) as c2
FROM
    table1 AS t1
    LEFT JOIN table2 as t2
        ON t1.id = t2.id2 AND t2.cond = 1
    LEFT JOIN table2 as t3
        ON t3.id2 = 2 AND t3.cond = 1

GROUP BY
    t2.id2,
    t3.id2

Can you provide schema?

Upvotes: 1

Related Questions