sql >> Databasteknik >  >> RDS >> Mysql

Välj data från olika kolumner och två tabeller

Bara JOIN med denna tabell USD :

SELECT sub.*, USD.USD
FROM
(
  SELECT 
    t1.id_auction,
    t2.bidder_1 AS bidder,
    t2.item,
    1 AS bidder_number    
  FROM table1 t1
  INNER JOIN table1 t2  ON t1.id_auction = t2.id_auction
                       AND t2.winner_1 = 1
  UNION ALL
  SELECT 
    t1.id_auction,
    t2.bidder_2 AS bidder,
    t2.item,
    2                    
  FROM table1 t1
  INNER JOIN table1 t2  ON t1.id_auction = t2.id_auction
                       AND t2.winner_2 = 1
) AS sub
INNER JOIN USD ON sub.id_auction = USD.id_auction
ORDER BY id_auction, bidder;

Uppdaterad SQL Fiddle Demo

| ID_AUCTION |  BIDDER | ITEM | BIDDER_NUMBER | USD |
-----------------------------------------------------
|          1 |   Alice |  cup |             1 | 100 |
|          1 |     Ben |  cup |             2 | 100 |
|          2 |   Alice |  mug |             2 | 150 |
|          3 |     Ben |  pen |             1 |  50 |
|          3 | Charles |  pen |             2 |  50 |


  1. Lagra HTML säkert i DB utan att påverka teckenkodningen

  2. Förvandla datum till datumintervall i MYSQL --- hur man hanterar luckor i datumen

  3. Hur sparar man en Google Maps-överläggsform i databasen?

  4. SQLAlchemy eller psychopg2?