简体   繁体   中英

MySQL select multiple columns into one

I have two tables

card_index

+-----+-----+-----+-----+
| uid | id1 | id2 | id3 |
+-----+-----+-----+-----+
|  1  | 125 | 129 | 145 |
|  2  | 127 | 128 | 132 |
+-----+-----+-----+-----+

and card_data

+----+------------+----------+...
| id |  last_use  |  active  |
+----+------------+----------+...
| 125| 10-07-2014 |   true   |
| 127| 27-02-2014 |   true   |
| 128| 15-06-2014 |   true   |
| 129| 10-01-2013 |   false  |
+----+------------+----------+... and so on

I want to select all data from 'card_data' by 'uid' from 'card_index', so the result for 'uid' = 1 should look like this:

+----+------------+----------+
| id |  last_use  |  active  |
+----+------------+----------+
| 125| 10-07-2014 |   true   |
| 129| 10-01-2013 |   false  |
| 145| 13-01-2013 |   true   |
+----+------------+----------+

The SQL query I made is:

SELECT * FROM card_data WHERE id IN (SELECT CONCAT(id1,',',id2,',',id3) FROM card_index WHERE uid = 1);

However it only selects firts row:

+----+------------+----------+
| id |  last_use  |  active  |
+----+------------+----------+
| 125| 10-07-2014 |   true   |
+----+------------+----------+

Can anyone help me? I don't know what's wrong. I'm using mysql-server 5.5.38-log, compiled from source on FreeBSD

Using INNER JOIN instead of combination of CONCAT and WHERE id IN worked for me. Here's the query:

SELECT * FROM card_data
INNER JOIN card_index ON id1=id OR id2=id OR id3=id
WHERE uid = 1;

And the desired result:

+----+------------+----------+
| id |  last_use  |  active  |
+----+------------+----------+
| 125| 10-07-2014 |   true   |
| 129| 10-01-2013 |   false  |
| 145| 13-01-2013 |   true   |
+----+------------+----------+

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