Mysql - 如何让所有记录都在同一个表的其他列中

时间:2014-12-31 18:47:40

标签: mysql

我有一张这样的表(mytable):

+------------+-----------+----------------+
| id_mytable | id_artist | foreing_column |
+------------+-----------+----------------+
|          1 |         2 |              5 |
|          2 |         1 |              5 |
|          3 |         1 |              2 |
|          4 |         3 |              6 |
+------------+-----------+----------------+

但是我只知道列foreign_column的第5个,知道这个5,我可以得到所有的id_artist(在这种情况下是2和1)

SELECT id_artist FROM `artist_band` WHERE id_band= 5

所以现在的问题是我想在这种情况下得到两个id_artist(1,2)的foreign_column,所以我最终得到这个表:

    +------------+-----------+----------------+
    | id_mytable | id_artist | foreing_column |
    +------------+-----------+----------------+
    |          1 |         2 |              5 |
    |          2 |         1 |              5 |
    |          3 |         1 |              2 |
    +------------+-----------+----------------+

(你知道所有的2和所有1都在foreign_column中)

我尝试过这样的事情:

(SELECT id_artist FROM `artist_band` as one WHERE id_band= 5)

inner join

(SELECT * FROM `artist_band` as two )

on one.id_artist = two.id_artist

或:

SELECT * FROM `artist_band` where id_artist =

(SELECT id_artist FROM `artist_band` WHERE id_band= 5)

感谢。

1 个答案:

答案 0 :(得分:2)

SELECT *
FROM mytable
WHERE id_artist 
IN 
 (
    SELECT id_artist 
    FROM mytable
    WHERE foreign_column = 5 -- (or whatever)
 )