简体   繁体   中英

mysql get all other rows how have same id from same table

I have two tables !

Songs:

|---------------------|------------------|------------------|
|      Title          |         ID       |      Version     |
|---------------------|------------------|------------------|
|   songnumber1       |         34       |    original      |
|---------------------|------------------|------------------|
|   songnumber2       |         35       |      remix       |
|---------------------|------------------|------------------|
|   songnumber3       |         36       |      remix       |
|---------------------|------------------|------------------|

And I have Other table to make references between songs reference:

|---------------------|------------------|------------------|
|         ID          |      remix       |      original    |
|---------------------|------------------|------------------|
|         1           |        35        |        34        |
|---------------------|------------------|------------------|
|         2           |        36        |        34        |
|---------------------|------------------|------------------|

What I want is to display the related songs below of the current song let's say $id is the ID of the current song which is 35 I want to display all other songs remix and the original also I tried this but it get just the original if $id is remix:

SELECT * FROM reference
         INNER JOIN songs ON reference.remix = songs.id OR 
reference.original = songs.id
         WHERE reference.original = '$id' OR reference.remix = '$id' 

I think this is what you want:

SELECT * FROM reference r
INNER JOIN songs a ON r.remix = a.ID  
INNER JOIN songs b ON r.original = b.ID
WHERE r.remix = 35

It would help if you post the expected results. Maybe this is what you want:

SELECT * FROM reference r
INNER JOIN Songs a ON r.remix = a.ID  
WHERE r.remix = 35
UNION  
SELECT * FROM reference r
INNER JOIN Songs b ON r.original = b.ID
WHERE r.remix = 35

Try this:

SELECT 
  C.currently_playing, 
  GROUP_CONCAT(DISTINCT IF(C.currently_playing=C.id,C.title,null)) current_song_title, 
  GROUP_CONCAT(DISTINCT IF(C.version='original',C.id,null)) orignial_song_id,
  GROUP_CONCAT(DISTINCT IF(C.version='original',C.title,null)) orignial_song_title, 
  GROUP_CONCAT(DISTINCT IF(C.version='remix',C.id,null)) related_remix_ids, 
  GROUP_CONCAT(DISTINCT IF(C.version='remix',C.title,null)) related_remix_titles 
FROM
  (SELECT 35 AS currently_playing, A.*
   FROM Songs   A 
   RIGHT JOIN (SELECT * FROM `references` WHERE remix=35 or original=35) B
   ON A.id IN (B.original,B.remix)) C
GROUP BY C.currently_playing;

See a working Demo on SQL Fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM