sql >> Database teknologi >  >> RDS >> Mysql

Hvordan får jeg denne SQL-forespørgsel til at udskrive to rækker i stedet for to felter?

Jeg kalder dette MySQL-hacking..

select @a as one
from
(

    SELECT @a := a.id, @b := b.id
    FROM Rankable a
    INNER JOIN Rankable b on a.id < b.id
    WHERE 
      a.category_id = ? AND b.category_id = ?
      AND NOT EXISTS (
        SELECT *
        FROM Comparison c
        WHERE c.lower_id in (a.id, b.id))
      AND NOT EXISTS (
        SELECT *
        FROM Comparison c
        WHERE c.higher_id IN (a.id, b.id))
    ORDER BY a.id * rand()
    LIMIT 1
) SQ
union all
select @b

For at deltage i tabellen for at få alle andre kolonner:

select Rankable.*
from
(
    select 1 as Sort, @a as one
    from
    (

        SELECT @a := a.id, @b := b.id
        FROM Rankable a
        INNER JOIN Rankable b on a.id < b.id
        WHERE 
          a.category_id = ? AND b.category_id = ?
          AND NOT EXISTS (
            SELECT *
            FROM Comparison c
            WHERE c.lower_id in (a.id, b.id))
          AND NOT EXISTS (
            SELECT *
            FROM Comparison c
            WHERE c.higher_id IN (a.id, b.id))
        ORDER BY a.id * rand()
        LIMIT 1
    ) SQ
    union all
    select 2, @b
) X
INNER JOIN Rankable ON Rankable.Id = X.one
ORDER BY X.Sort


  1. Rediger materialiseret visningsforespørgsel

  2. mysql_fetch_row() vs mysql_fetch_assoc() vs mysql_fetch_array()

  3. Hvorfor tilføjer Oracles to_char()-funktion mellemrum?

  4. CTE-sletning er ikke begået, før følgende udsagn er fuldført